Javascript tag attribute value

Element.getAttribute()

getAttribute() возвращает значение указанного атрибута элемента. Если элемент не содержит данный атрибут, могут быть возвращены null или «» (пустая строка); подробнее Notes.

Синтаксис

var attribute = element.getAttribute(attributeName);
  • attribute — переменная, которой будет присвоено значение attributeName .
  • attributeName — имя атрибута, значение которого необходимо получить.

Пример

var div1 = document.getElementById("div1"); var align = div1.getAttribute("align"); alert(align); // отобразит значение атрибута align элемента с

Примечания

Когда метод getAttribute вызывается применительно к HTML-элементу, в DOM HTML-документа, значение аргумента приводится к нижнему регистру.

В действительности все браузеры (Firefox, Internet Explorer, последние версии Opera, Safari, Konqueror, iCab и т.д.) возвращают null , когда выбранный элемент не содержит атрибута с переданным именем. Спецификация DOM определяет, что корректное возвращаемое значение в данном случае — пустая строка и некоторые реализации DOM придерживаются такого поведения. Реализация getAttribute в XUL (Gecko) в настоящее время следует спецификации и возвращает пустую строку. Следовательно, имеет смысл использовать hasAttribute, чтобы проверять наличие атрибутов перед вызовом getAttribute() , если может быть такое, что выбранный элемент не будет содержать искомого атрибута.

Методы DOM имеют дело с атрибутами элементов:

Не знают пространства имён, наиболее часто используемые методы Вариант, знающий пространство имён (Уровень DOM 2) Уровень DOM 1 методы для работы с Attr узлами напрямую (используется редко) Уровень DOM 2 знает о методах пространства имён для работы с Attr узлами напрямую (используется редко)
setAttribute (DOM 1) setAttributeNS (en-US) setAttributeNode (en-US) setAttributeNodeNS (en-US)
getAttribute (DOM 1) getAttributeNS (en-US) getAttributeNode (en-US) getAttributeNodeNS (en-US)
hasAttribute (DOM 2) hasAttributeNS (en-US)
removeAttribute (DOM 1) removeAttributeNS (en-US) removeAttributeNode (en-US)
Читайте также:  Web interface mysql php

Спецификации

Found a content problem with this page?

This page was last modified on 7 нояб. 2022 г. by MDN contributors.

Источник

How can I get the attribute value of an element in JavaScript?

For these types of questions, you usually get a better response if you start off with what you’ve tried and ask a more specific question about the issue you’ve run into. At the very least, explain why existing solutions (of which there are many) aren’t working in your case. A specification document for the code you want isn’t quite in the spirit of SO.

2 Answers 2

To get a NodeList of Nodes that match a selector

var list = document.querySelectorAll('[myAttribute]'); 

list will be Array-like but not inherit from Array. You can loop over it with for and list.length

To get a NamedNodeMap of the attributes on an Element

nnm will be Array-like but not inherit from Array. You can loop over it with for and nnm.length

To get the value of an attribute on an Element use .getAttribute

var val = elem.getAttribute('myAttribute'); 

val will be null if there is no such attribute

To test the existance of an attribute on an Element use .hasAttribute

var b = elem.hasAttribute('myAttribute'); 

b will be a Boolean value, true or false

Using jQuery you could do something like this.

div = $("[myAttribute]"); attrValue = div.attr('myAttribute'); 

div would be the jQuery element.
attrValue would be ‘ok’

SO is so weird. I have been around for a while and people are seriously crazy about the guidelines. I believe I had 16 reputation points when I wrote this answer. Yes, I misread the question, but I was still new to the game. In my heart I did not mean to offend anybody by answering the question poorly, I just meant to help. I can see why the site gets criticism. Anyway, I apologize for misreading this question and please feel free to downvote this question some more. It won’t keep me from trying to help in the future.

Источник

How to get html tag attribute values using JavaScript Regular Expressions?

You were so close! All that needs to be done now is a simple loop:

var htmlString = '\n'+ '\n'+ '\n'; var setCookieMetaRegExp = //ig; var matches = []; while (setCookieMetaRegExp.exec(htmlString)) < matches.push(RegExp.$1); >//contains all cookie values console.log(matches); 

So this only seems to work when content comes at the end of the tag. If an attribute follows content then it picks it up in the regexp. How to do you tell the matching to stop when it reaches the closing quote? Here is my bin of the problem. jsbin.com/xebimu/1/edit?js,console

Update (based on your comment):

runs only on this exact string. Demo: http://regex101.com/r/pT0fC2

You really need the (.*?) with the question mark, or the regex will keep going until the last > it finds (or newline). The ? makes the search stop at the first » (you can change this to [\»‘] if you want to match either single or double quote).

I need to run the regular expression specifically on set-cookie, and the HTML string is a complete HTML document

no need for regular expressions just do some dom work

var head = document.createElement("head"); head.innerHTML = ''; var metaNodes = head.childNodes; for(var i=0; i

As you are using nodejs and BlackSheep mentions using cheerio you could use their syntax if you wish to use that lib:

//Assume htmlString contains the html var cheerio = require('cheerio'), $ = cheerio.load(htmlString); var values=[]; $("meta").each(function(i, elem) < values[i] = $(this).attr("content"); >); 

Источник

How get tag attribute by javascript without using id or class?

But in tag I don’t want to use any id or class. How can I get this attribute without using any id or class in a tag.

Are you only trying to get the element from within the cheak function? If so, Zain’s answer is the correct one.

Side note: That href is incorrect. It should be href=»http://facebook.com» or href=»https://facebook.com» . Just href=»facebook.com» is a relative URL.

3 Answers 3

Preface: Below, I’ve answered the question of how to find an element without using an id or class , in the general case. But if you just want the element from within your cheak function, then Zain’s answer is the correct way to do that (with minimal changes to your code; arguably more correct might be modern event hookup).

But in tag I don’t want to use any id or class. How can I get this attribute without using any id or class in a tag.

You reach for the Swiss army knife of element selection: document.querySelector . With it, you can use any CSS selector that matches the element:

var href = document.querySelector("any selector here").getAttribute("href"); 

querySelector returns the first match in the document. (There’s also querySelectorAll , which returns a list.) They’re both supported in all modern browsers, and also IE8.

Since you have the full power of CSS selectors, you can use anything about the position of the element in the document to find it.

There’s too little context in your question for a specific example, but for instance if it’s the first a in the document:

var href = document.querySelector("a").getAttribute("href"); alert(href);
var href = document.querySelector("a[onclick='cheak()']").getAttribute("href"); alert(href);

Источник

Оцените статью