Get element which have a specific data-* set - javascript

Say, I've a <script data-src = "script.js"> somewhere in my DOM without any id or other identifiable attribute set. How could I select that element so that I can reset that element with correct src.
Like:
var el = //code
el.src = el.dataset.src;
Maybe I could loop all script tag and all, but is there a way to get specific element by just this info?
EDIT:
With pure javascript.

you can use query selector as following :
element = document.querySelectorAll("script[data-src]")[0];

This can be done with JavaScript's querySelectorAll()
// Get the first script tag with the data attribute "data-src"
var theScript = document.querySelectorAll("script[data-src]")[0];
// write the data-src to the document
document.write(theScript.getAttribute('data-src'));
<script data-src="testing.js"></script>

Use $(document).find('[data-src]') to get the object. Note, if you have more objects with data-src then you have to loop through them.
$(document).find('script[data-src]').attr("data-src", "News link")
console.log($(document).find('script[data-src]').data("src"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script data-src="script.js"></script>

Try this...
with pure Js.
var el=document.querySelector('script[data-src]');
console.log(el.dataset.src);
el.dataset.src='correct-src.js';
console.log(el.dataset.src);
<script data-src = "script.js">
</script>
<div></div>

jQuery:
$("script[data-src='script.js']")
For more details https://api.jquery.com/category/selectors/
Javacript:
document.querySelector('[data-src="script.js"]')
Form more details see here

Related

How to get the value of an attribute?

Trying to get the value of a specific tag in HTML, but I can't find a proper way to do it.
Let's say I have the following HTML code:
<body id="en" class="that-great-class " number_id="1534" support="clp" source="desktop">
How can I get the value from number_id, support and source ?
Already tried this but doesn't work.
document.getElementsByTagName("number_id");
Thanks.
So your js is only slightly off, you are using getElementsByTagName which will get HTML elements by their tag e.g. body tag, header tag, div tag and so on.
You are wanting to get the attribute of the body tag so you first would need to get the body tag.
const bodyTag = document.getElementsByTagName("body")[0];
This gets all elements with the tag name of body and puts them in the array, but there should only be 1 body tag so you get the first.
You then want to get the attribute of 'number_id', to do this, you would do
const numberId = bodyTag.getAttribute("number_id");
document.querySelectorAll('[number_id="1534"]')
The related docs are Attribute_selectors and querySelectorAll
Your method name is incorrect it should be plural if you use tagName getElementsByTagName
But didn't actually correct with what you are trying to use
Getting element by tag means like HTML tags Ex - li, h1 body not
their attributes
Use querySelector instead.
const el = document.querySelector("[number_id='1534']")
console.log(el)
<body id="en" class="that-great-class " number_id="1534" support="clp" source="desktop">
Have you tried this?
var id = document.getElementById("en").getAttribute("number_id");

very simple but can't resolve. grabbing element

i'm trying to get the value from the ID => vname into the variable name
and the return should be "Loren",
I tried with and without the value attribute call but doesn't work. what am i missing?
<html>
<head>
<script>
var name = document.getElementById("vname").value;
alert(name);
</script>
</head>
<body>
<p id="vname" value="firstname">Loren</p>
</body>
</html>
There are three things wrong here:
You are trying to access the element before it exists You cannot eat the pizza before it is delivered... See Why does jQuery or a DOM method such as getElementById not find the element? for more info.
<p> HTML elements do not have a value attribute. In your case, value is a non-standard HTML attribute. If you want to use custom attributes, use data-* attributes instead.
p DOM elements do not have a value property. Only form control elements (input, select, etc) have such a property. If you want to get the content of an element, use innerHTML or textContent instead.
If you had opened your browser's console, you would have seen an error, because the element with ID vname couldn't be found. Make yourself familiar with your browser's developer tools so that you can fix issues like this on your own.
You can't get the "value" of a p element, you have to get the "innerHTML"
try this: var name = document.getElementById("vname").innerHTML;
Try var name = document.getElementById("vname").innerHTML;
When you try to access the #vname is not in the DOM yet. You will need to add the script tag after the element or wait for the DOM to be loaded.
When that is said a <p> tag cannot have a value. Use data-value instead:
<p id="vname" data-value="firstname">Loren</p>
<script>
var vname = document.getElementById("vname");
var value = vname.getAttribute('data-value');
console.log(value);
</script>

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

I am new in javascript.I am trying this below code to get href attribute.
Facebook
<script type="text/javascript">
function cheak()
{
var a= document.getElementsByTagName("a").getAttribute('href');
alert(a);
}
</script>
I know this is working by below code
document.getElementById("myid").getAttribute('href'); // if I use any id
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.
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);
Facebook
Or using that onclick:
var href = document.querySelector("a[onclick='cheak()']").getAttribute("href");
alert(href);
Facebook
If you pass in this when calling the function. it will pass the element reference to your function and you can use it to get value of href:
Facebook
<!-- Note -----------------------------^^^^ -->
<script type="text/javascript">
function cheak(a) {
alert(a.href); // Gives you the fully-resolved URL
alert(a.getAttribute("href")); // Gives you the content of the `href` attribute (not fully-resolved)
}
</script>
the parameter data is the complete tag on which the function is called
Facebook
<script type="text/javascript">
function cheak(e)
{
e.preventDefault();
// var a= document.getElementsByTagName("a").getAttribute('href');
alert(e.target);
}
</script>

Create and remove HTML-Element dynamically

How can I create a HTML-Element dynamically, do something with it and then it should be removed.
But it is important that it will be really deleted.
Here is my approach:
var newdiv = document.createElement('div');
newdiv.setAttribute('id','MyDiv');
$('#MyDiv').css({'width':'100px','height':'100px'});
$('#MyDiv').html('This is a test');
$('#MyDiv').remove(); // It should be work ?
// Is it possible to delete it as follows?
newdiv.remove();
As I mentioned, it is important to really delete the element, since the Function "createElement()" can often get invoked.
How can I test whether the new created HTML-Element is really removed?
I test as follows, whether the element is still existed, but I get always true!
alert( $('#MyDiv').length == 1);
Below are a two links, but they were not enough for, in order to solve my problem.
setting the id attribute of an input element dynamically
createElement and delete DOMElement
Thanks.
try this one maybe is what you want:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var div = document.createElement("div");
$(function(){
$("body").append( div);
$(div).css({'width':'100px','height':'100px','border':'solid 1px black'}).html('This is a test');
//$(div).remove();
});
</script>
</head>
<body>
</body>
</html>
dont forget to uncoment the //$(div).remove();
First of all, I see, you have an error in your code in this line:
newdiv.setAttribute('id','#MyDiv')
value of id attribute must not have '#' (the hash sign) - with your code element newdiv will have id like "#MyDiv" but this is not valid ID for jQuery, due to jQuery use this template for ID Selector (“#idName”)
You can dynamically delete the element with your way, but I guess previously you should to append it to another element on page using jQuery.append(you element/selector) method
If you can use jQuery you can try with the following:
$( "body" ).append( "<div id="MyDiv">This is a test</div>" ); // Create MyDiv div before </body> tag (you can use .prepend( ... ) to create it after <body>)
$("#MyDiv").css({'width':'100px','height':'100px'}); // Give some style to MyDiv
$("#MyDiv").remove(); // Delete MyDiv

Find and assign content to a variable

What I need is to find an element which have class="selected" and than assign content of that element to a variable.
This is the content
This is the content
This is the content
Any help? Thank you
Use the class operator:
var elementContents = $('.selected').html(); //assuming there is only one element found with the class selected
Hope this helped.
var someContent = $('.selected').html();
var variable=$(".selected").text();
DEMO
Give it an Id, then use:
var content = document.getElementById("yourIdHere").innerHTML;
to ensure you only get the first occurance, don't forget to instruct jQuery to only get the first, and to ensure it's readable i'd use the .text() not the .html() selector as it will strip any HTML away if there is any
This is the content
This is the content
This is the content
<script type="text/javascript">
$(document).ready(function() {
var myVariable = $(".selected").first().text();
});
</script>

Categories