jQuery从元素中选择文本排除子元素

时间:2014-02-21 11:05:27

标签: jquery

var machine = $('h1').contents(':not(small, a)').text();
console.log(machine);

<h1>Title <small>subheading</small> <a href="#"></a></h1>

我正在尝试使用上面的jQuery显示Title的文本,但当然这个console.logs是一个空白行。基本上不包括smalla代码

jsFiddle

1 个答案:

答案 0 :(得分:1)

var machine = $("h1")
.clone()    //clone the element
.children() //select all the children
.remove()   //remove all the children
.end()  //again go back to selected element
.text();

alert(machine);