How to reference id and get href of a link? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Question : How to reference id of a link? See the attached image
Click here
function insertButton(refresh = false) {
var to_match = 'a[class="';
var PAGE_TYPE = 0;
if (document.location.href == "https://www.youtube.com") {
How to reference id = "video-title-link"
var anchor_tag = document.getElementById("video-title-link");
There are 2 anchor tags* with the same class name. I would like to reference the id ="video-title-link"
if(anchor_tag.hasAttribute('href="\/watch\?v=(\S+)"')){
to_match = to_match.concat("yt-simple-endpoint style-scope ytd-rich-grid-video-renderer", '"]').getattribute('id ="video-title-link"');
PAGE_TYPE = 1;
}
}
UPDATE : POLLING
const poller = setInterval(function(){
const anchor_tags = document.querySelectorAll('a[id="video-title-link"]');
if(anchor_tags){
for (index = 0; index < anchor_tags.length ; index++){
console.log(anchor_tags[index].getAttribute('href'));
}
clearInterval(poller);
}
}, 1000);
OUTPUT : Click here : href of each 'id'

You can use querySelector() and .getAttribute() to do this:
const element = document.querySelector(".yt-simple-endpoint")
const href = element.getAttribute("href");
console.log(href)
<a class="yt-simple-endpoint" href="https://example.com">Link</a>

Related

How to call querySelector for different class? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Need to make a webpart which gets data from API in JSON format. I generate a table from JSON with projects number. Then I change each td to link with class="project_number".
Now each position has it's specific class. No I need each link to direct to project details ot url like: https://XXX.azurewebsites.net/api/protocollines?protocolNo=PR0002
I don't know what parameter should I place in querySelector to have addEventListener for each link.
document.querySelector("???").addEventListener('click', *function*);
function changeToLink(){
var tableCells = Array.from(document.getElementsByTagName('td'));
var i;
var proNo = "PR0";
for (i=0; i<tableCells.length; i++ && isContains == true) {
var proFromArray = tableCells[i].innerHTML;
var isContains = proFromArray.includes(proNo);
if(isContains == true){
var tdElement = document.getElementsByTagName('td')[i];
console.log('Profrom: ' + proFromArray);
tdElement.innerHTML = `<a class="${proFromArray}" href='https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}'>${proFromArray}</a>`
}
}
}
document.querySelector(`??`).addEventListener('click', *function*);
There's a few ways to do this.
Option 1
You could create the anchor elements using JS, and add the onclick event when you create each one, like:
// inside the if(isContains == true){
var a = document.createElement('a');
a.className = proFromArray;
a.href = `https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}`;
a.textContent = proFromArray;
a.onclick = this.getJsonData;
I created a Fiddle to demonstrate how it works: https://jsfiddle.net/brettnolf/f3xd7ag1/
Option 2
Now, if you need to create it in the form of a string and later call querySelector on what you created, you could add the same class to each anchor tag:
tdElement.innerHTML = `<a class="${proFromArray} pro-elem" href='https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}'>${proFromArray}</a>`
Then add the event listener, like:
var pros = document.querySelectorAll('.pro-elem')
for (var i = 0; i < pros.length; i++) {
pros[i].addEventListener(this.getJsonData);
}
Option 3
If both of those solutions are out of the question, you could use a query selector wildcard and add the event listener similar to the above:
var pros = document.querySelectorAll('[class^=PR0]')
// or if you wanted to be really specific:
// document.querySelectorAll('td a[class^=PR0]')
for (var i = 0; i < pros.length; i++) {
pros[i].addEventListener(this.getJsonData);
}
You can see this last solution in action if you pull up Chrome dev tools here https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll and enter document.querySelectorAll('[class^=title]') in the Console.
Note that the last two options will only work after the elements have been added to the DOM. In the first option, you add the listener when you create the element, so you do it on the fly.

how can I add onclick by for loop, for mr[2] and test1[2] [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
how can I add onclick by for loop, for mr[2] and test1[2]
I have more buttons and iframes
mr[2].onclick = function selectItem() {
for (var i = 0; i < mr.length; i++) {
mr[i].classList.remove('selected');
mr[i].style.backgroundColor = 'rgba(21,21,21,1)';
};
this.classList.add('selected');
this.style.backgroundColor = '#ff5722';
for (var i = 0; i < test1.length; i++) {
test1[i].setAttribute('src', 'https://upload.wikimedia.org/wikipedia/commons/0/0c/Olive_green_check.svg');
test1[i].style.display = 'none';
};
test1[2].setAttribute('src', 'www.google.com');
test1[2].style.display = 'block';
};
Consider maybe simply use the DOM Element method addEventListener on the obejcts you want to add the "onclick" property to as a possible solution:
https://www.w3schools.com/JSREF/met_document_addeventlistener.asp
mr[2] is button 2 from 5 buttons and test1[2] is iframe 2 from 5 iframes

Translate simple Jquery to VanillaJS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have this: $('#night > li').appendTo('#day');
The code moves all <li> elements of <ul id="night"> to the end of <ul id="day">.
Please, how can I translate this into VanillaJS?
I mean, how do I rewrite the code so I do not need Jquery?
Have this so far:
document.getElementById('night').li.appendTo.document.getElementById('day');
In pure JavaScript you could do it like this:
var night = document.getElementById("night");
var day = document.getElementById("day");
var lis = document.querySelectorAll("#night > li");
for (var i = 0, len = lis.length; i < len; i++) {
day.appendChild(lis[i]);
}
See fiddle for working example.
Could look like so
var target = document.getElementById( 'day' );
[].forEach.call(document.querySelectorAll( '#night > li' ), function( li ) {
day.appendChild( li );
});
You can try something like this:
var dayUl = document.getElementById("day");
var nightUl = document.getElementById("night");
var nightLis = nightUl.childNodes;
for (var i = 0, len = nightLis.length; i < len; i++)
{
dayUl.appendChild(nightLis[i]);
}
Also, you can go with #Marcus Ekwall's solution, but keep in mind that the solution isn't fully compatible with IE8 or below, and the first query for the night node is redundant (because below he searches for #night > li)

How to apply javascript code on dynamiclly added elements using javascript not JQuery? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I wrote a code that transform each word in an article to a link, and i wanted to apply onclick() function on the new anchors but the code is not working..
here is the javascript code:
<script>
var tarea = document.getElementById("t");
var div = document.getElementById('res');
var article = tarea.innerHTML;
var i=0;
while(i<500 ){
var ind = article.indexOf(" ");
var curr = article.substring(0,ind);
article = article.substring(article.indexOf(" ")+1);
anch = "<a class='link' id='link' href='#' >" + curr+"</a>";
div.innerHTML = div.innerHTML + " " + anch;
i++;
}
var element = document.getElementById('link');
element.onclick = function () {
alert(element.innerHTML);
};
</script>
This is called event delegation. It can get complicated, but this is the basic concept. You can use anything that can identify the element, but I just used id here since that is the most simple.
var MY_DYNAMIC_EL_ID = 'dynamic';
window.addEventListener('click', function(e) {
var el = e.srcElement || e.target;
if(el.id == MY_DYNAMIC_EL_ID) {
alert('clicked');
}
}
var el = document.createElement('div');
el.id = MY_DYNAMIC_EL_ID;
document.body.appendChild(el);
http://jsfiddle.net/B7Ja9/6/

(JQuery) I'm wondering why this code doesn't work? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have narrowed it down to the line that declares the 'position'
$(document).ready(function(){
var sliders = new Array("#left","#middle","#right");
var links = new Array("#fLink","#sLink","#tLink");
$(".link").click(function(){
var position = $("#" + sliders[links.indexOf("#" + this.id)]).position().left();
alert(position);
$(".slider").animate({left:gap}, 1500);
});
});
sliders already has the # in it, you don't want to add it again when using it within $(), you end up passing "##left" in as the selector string. Also note that left is a value, not a function, so no () after it.
So:
var position = $("#" + sliders[links.indexOf("#" + this.id)]).position().left();
// Remove -------^^^^^^ and -------------------------------------------------^^
For what you're doing, I wouldn't use a pair of arrays, I'd use:
A lookup object, or
A naming convention, or
A data-* attribute
The last two are trivial, but here's how that first one would work:
$(document).ready(function () {
var sliders = {
"fLink": "#left",
"sLink": "#middle",
"tLink": "#right"
};
$(".link").click(function () {
var sliderSel = sliders[this.id];
if (sliderSel) {
var position = $(sliderSel).position().left;
alert(position);
$(".slider").animate({
left: gap
}, 1500);
}
});
});
Side note: Is gap defined somewhere in code you haven't shown? If not, you'll want to do that.

Categories