JQuery - 在中选择文本并在中包装

时间:2022-11-29 10:37:14

I know that this:

我知道这个:

$("#id").html().split("<br>")[1];

gets 'Song name' from the HTML below.

从下面的HTML中获取“歌曲名称”。

How do I then wrap 'Song name' in a < span > in the HTML?

如何在HTML中的中包装“歌曲名称”?

HTML:

<a href="http://www.google.com" id="id">
  252. 
  <br>
  Song name
  <br>
  — Song Title
</a>

SOLVED!

See my answer below

请参阅下面的答案

3 个解决方案

#1


I guess wrapInnerfunction is what you are looking for

我想wrapInnerfunction就是你要找的东西

https://api.jquery.com/wrapinner/

#2


I can see the logic in the other answers but neither of them worked. Seems as though I couldn't put anything after

我可以在其他答案中看到逻辑,但它们都没有奏效。好像我不能放任何东西

$("#id").html().split("<br>")[1]

...without it being deemed 'not a function' in console.

......没有它在控制台中被视为“不是一个功能”。

In the end I achieved what I wanted to by storing various chunks of code in variables and splicing them together e.g.

最后,我通过在变量中存储各种代码块并将它们拼接在一起,实现了我想要的目标,例如:

var middleLineOfTitle = data.response.posts[i].title.split("<br />")[1];
var middleLineOfTitleWrapped = "<span class='middleLineOfPostNameClass'>" + middleLineOfTitle + "</span>";
var entireTitle = data.response.posts[i].title.replace(middleLineOfTitle, middleLineOfTitleWrapped);

$('#recent-posts').append('<li><a href="' + data.response.posts[i].post_url +'"> ' + entireTitle + '</li>');

#3


Try this:

$("#id").html().split("<br>")[1].prepend("<span>").append("</span>");

#1


I guess wrapInnerfunction is what you are looking for

我想wrapInnerfunction就是你要找的东西

https://api.jquery.com/wrapinner/

#2


I can see the logic in the other answers but neither of them worked. Seems as though I couldn't put anything after

我可以在其他答案中看到逻辑,但它们都没有奏效。好像我不能放任何东西

$("#id").html().split("<br>")[1]

...without it being deemed 'not a function' in console.

......没有它在控制台中被视为“不是一个功能”。

In the end I achieved what I wanted to by storing various chunks of code in variables and splicing them together e.g.

最后,我通过在变量中存储各种代码块并将它们拼接在一起,实现了我想要的目标,例如:

var middleLineOfTitle = data.response.posts[i].title.split("<br />")[1];
var middleLineOfTitleWrapped = "<span class='middleLineOfPostNameClass'>" + middleLineOfTitle + "</span>";
var entireTitle = data.response.posts[i].title.replace(middleLineOfTitle, middleLineOfTitleWrapped);

$('#recent-posts').append('<li><a href="' + data.response.posts[i].post_url +'"> ' + entireTitle + '</li>');

#3


Try this:

$("#id").html().split("<br>")[1].prepend("<span>").append("</span>");