Get HTML attribute value using JavaScript

I have a website on which I transmit information to the analytics engine through the meta tag as such:

<meta property="analytics-track" content="Hey&nbsp;There!">

I am trying to write a JavaScript script (without libraries) to access the content section and get the information as is. Essentially, it should include an HTML object, not transform it.

The reason is because I use PhantomJS to check which pages have HTML objects in the metadata and delete them, because they messed up my analytic data (for example, I will have records containing both Hey There!, and Hey&nbsp;There!when in fact they are one and same page and therefore should not have two separate data points).

The simplest JS format I have is:

document.getElementsByTagName('meta')[4].getAttribute("content")

And when I examined it on the console, it returns the text in the following format:

"Hey There!"

I would like him to return:

"Hey&nbsp;There!"

How can I guarantee that the returned data will contain an HTML object. If this is not possible, there is a way to detect the HTML object through JavaScript. I tried:

document.getElementsByTagName('meta')[4].getAttribute("content").includes('&nbsp;')

But it returns false

+4
source share
3 answers

Use queryselector to select an element with the value of the analytics-track property, outerHTML to get the element as String and match to select the unparameterized value of the content property using Regex.

document.querySelector('[property=analytics-track]').outerHTML.match(/content="(.*)"/)[1];

See http://jsfiddle.net/sjmcpherso/mz63fnjg/

+4
source

, &nbsp; . . , DOM, -, , :

Hey There!

, y T , , , .

:

<span id='a' data-a='Hey&nbsp;There!'></span>
<span id='a1' data-a='Hey&nbsp;There!'></span>
<span id='b' data-b='Hey There!'></span>

var a = document.getElementById('a').getAttribute('data-a')
var a1 = document.getElementById('a1').getAttribute('data-a')
var b = document.getElementById('b').getAttribute('data-b')
console.log(a,b,a==b)
console.log(a,a1,a==a1)

:

Hey There! Hey There! false
Hey There! Hey There! true

"" :

var re = '/(\xC2\xA0/|&nbsp;)';
x = x.replace(re, ' ');
+2

HTML- , outerHTML:

document.getElementsByTagName('meta')[4].outerHTML

:

console.log(document.getElementsByTagName('meta')[0].outerHTML);
<meta property="analytics-track" content="Hey&nbsp;There!">
<h3>Check your console</h3>
Hide result

Element.outerHTML - -API | MDN


1:

-, :

metaInfo.match(/content="(.*)">/)[1];  // assuming that content attribute is always at the end of the meta tag

:

var metaInfo = document.getElementsByTagName('meta')[0].outerHTML;

console.log(metaInfo);

console.log('Meta Content = ' + metaInfo.match(/content="(.*)">/)[1]);
<meta property="analytics-track" content="Hey&nbsp;There!">
<h3>Check your console</h3>
Hide result
+1
source

Source: https://habr.com/ru/post/1616131/


All Articles