I am trying to get the text of the link directly before another link (parent's sibling), but I keep getting "undefined." I can't figure out what I need to change to get the anchor tag's text rather than "undefined"
Here is my HTML:
<li class="dropdown extra-class-a extra-class-b">
<a class="level-1 extra-class1 extra-class2" href="#">Home Menu 1</a>
<ul class="someclass" >
<li class="some-class3"></li>
<li class="no-subcat last" data-moburl="#" data-cgid="other-text">
<a class="level-2" href="#"> Shop Text </a>
</li>
</ul>
</li>
Here is my script. Note that I am adding this to Adobe DTM as an onclick event, so I'm not actually sure how to debug this using console.log. If someone could also explain how to do that, it would be helpful.
This is based on Cory's suggestion below, but in the last line where I am expecting home menu 1>shop text I get >shop text (i.e., the value for 'par' is blank
var $x = $(this);
//get parent link element (i.e., HN1 value)
var par = $x.closest('[class*="dropdown"]').find('a[class^="level-1"]').text(); ;
//get value of link clicked
var clicked = $x.text();
//expecting "home menu 1>shop text"
//currently returns ">shop text"
var finalValue = par + '>' + clicked;
The
jQuery
library functionality is accessed through the function$
orjQuery
, which you seem to have omitted from your code.(x)
with$(x)
orjQuery(x)
, ORthis
with$(this)
orjQuery(this)
.The result of either of the above will be a properly wrapped jQuery element, giving you access to
closest()
,prev()
, and the other jQuery functions you are attempting to use in your code.In jQuery-land, it's helpful to name variables so you know they are wrapped. For the rest, I'm going with the second option from above, and so I will change the name of
x
. Your fixed code might look something like: