1

Hi guys i got an <a> tag which look like this:

<a class="js-swatch-item-link swatch__item-inner-image" data-layer-click="{"event":"interaction","interaction":{"category":"colorPattern","action":"Select","label":"DARK GREY MELANGE","value":"DARK GREY MELANGE"}}}" href="#">DARK GREY MELANGE</a>

I am trying to fetch the value of the interaction section of the JSON string, and then afterwards assigning this value to the innerHTML of the <a> tag.

My JavaScript code looks like this:

var SWATCH_COLOR_LINK = '.swatch.colorpattern a';
var swatchColorLink = document.querySelectorAll(SWATCH_COLOR_LINK);
var swatchColorTitle = JSON.parse(swatchColorLink.getAttribute('data-layer-click')).interaction.value;

for (var i = 0; i < swatchColorLink.length; i++) {
    swatchColorLink[i].innerHTML = swatchColorTitle;
}

The function is giving me the following error: swatchColorLink.getAttribute is not a function

However if I try to just select the first element like this: document.querySelectorAll(SWATCH_COLOR_LINK)[0]

The function works fine and sets the right value from the JSON string to the innerHTML of the <a> tag.

Im guessing im doing something wrong in my loop to go over all <a> tags and assigning them the value of their JSON string.

2

2 Answers 2

1

Your mistake is laying in swatchColorLink.getAttribute(). Because your swatchColorLink's value is a NodeList which is returned from querySelectorAll() method. When you are doing document.querySelectorAll(SWATCH_COLOR_LINK)[0] you are getting the first element from this NodeList so in this case your swatchColorLink is the single node.

var SWATCH_COLOR_LINK = '.swatch.colorpattern a';
var swatchColorLink = document.querySelectorAll(SWATCH_COLOR_LINK);


for (var i = 0; i < swatchColorLink.length; i++) {
    var swatchColorTitle = JSON.parse(swatchColorLink[i].getAttribute('data-layer-click')).interaction.value;
    swatchColorLink[i].innerHTML = swatchColorTitle;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I send you kisses ! Thanks for your answer, this helped a lot.
1

Correct your JSON string {"event":"interaction","interaction":{"category":"colorPattern","action":"Select","label":"DARK GREY MELANGE","value":"DARK GREY MELANGE"}}}

you should escape the quotes " in the string and remove the last }

<a class="js-swatch-item-link swatch__item-inner-image" data-layer-click="{\"event\":\"interaction\",\"interaction\":{\"category\":\"colorPattern\",\"action\":\"Select\",\"label\":\"DARK GREY MELANGE\",\"value\":\"DARK GREY MELANGE\"}}"href="#">DARK GREY MELANGE</a>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.