我如何从段落元素中获取姓氏

时间:2016-01-12 09:20:06

标签: javascript

我怎样才能从JS <p>标签中获取姓氏,我已经修改了我的代码不正确,我该怎么做呢?

<p class="surname">Janet Garcia</p>

var surname = document.getElementsByClassName("surname")[0].lastElementChild.innerHTML;
console.log(surname);

3 个答案:

答案 0 :(得分:3)

除了类名错误之外,我认为这是一个简单的错字,获得元素文本内容的正确方法是令人惊讶的.textContent

var name = document.getElementsByClassName("surname")[0].textContent;
console.log(name); // "Janet Garcia"

从那里,你可以将名称分成几部分:

var nameparts = name.split(" ");
var surname = nameparts.pop(); // get the last one
console.log(surname); // "Garcia"

答案 1 :(得分:0)

var surnameParagraph = document.querySelectorAll("p.surname")[0];
var name = surnameParagraph.textContent;

var spaceIdx = name.indexOf(" ");

var firstName = name.substring( 0, spaceIdx );
var lastName  = name.substring( spaceIdx + 1 );

console.log( lastName );

答案 2 :(得分:-1)

我会用空格分割字符串,然后返回分割数组中的最后一个元素。第二个想法,我会把它从数组的末尾弹出。

var name = document.getElementsByClassName("name")[0].innerText,
    surname = name.split(' ').pop();

console.log( surname );
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
<p class="name">Janet Garcia</p>