Get tagname name value javascript

谁都会走 提交于 2021-01-28 05:21:41

问题


I'm trying to get the tagname of name from the below line of code. I have to get the name from the below tagname using javascript

<preference name="webviewbounce" value="false" />

i need to get webviewbounce

This is what i know.

document.getElementsByTagName("preference")

But it doesnt give me the preference name. What i want is the tagname of name which is webviewbounce


回答1:


Use document.querySelector to get the element. It will return the first matched element.Then use getAttribute to get the required attribute from the element. If there are multiple tag element with same tagname , use document.querySlectorAll

var getElem = document.querySelector('preference'),
  getNameProperty = getElem.getAttribute('name');
console.log(getNameProperty)
<preference name="webviewbounce" value="false" />



回答2:


Try:

document.getElementsByName("webviewbounce");

This will get the element that has the name of webviewbounce




回答3:


getElementsByTagName is going to return a collection of elements. You can then use getAttribute() to get the name property of the first item in the collection.

console.log( document.getElementsByTagName( "preference" )[0].getAttribute( 'name' ) );



回答4:


const p = document.getElementsByTagName('preference')

console.log(p[0])
// <preference name="webviewbounce" value="false">…</preference>

console.log(p[0].getAttribute('name'))
// webviewbounce
<preference name="webviewbounce" value="false" />



回答5:


Considering this as your first element of preference tag. this would give document.getElementsByTagName("preference")["0"].name the name. The "0" in the line code should be changed to the exact element.

In addition you can also use getAttribute('name') with getElementsByTagName().




回答6:


You can use getAttribute to get the name value of the tag.

You can try something like this.

var element = document.getElementByTagName("preference");
var name = element.getAttribute("name");
console.log(name);


来源:https://stackoverflow.com/questions/44015552/get-tagname-name-value-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!