How to find an element with a data attribute with unknown value? - javascript

I'm looking for a specific element which contain a known data attribute. The actual value of the data could be anything. Example:
<div id="myObject">
<div>
<span data-some-data="anything">something</span>
</div>
<div>
I'm trying to access the span tag in the above example.
I've tried something like:
var $theElementINeed = $('#myObject').find("[data-some-data='" + ??? + "']");
But the value could be anything. So I don't know how to find the span. Any suggestions?

If you just want to check for the existence of the attribute then use the has attribute selector
var $theElementINeed = $('#myObject').find("[data-some-data]");

Per this! discussion, try:$('element').find('[data-some-data]');

Related

jquery selecting div id within div id

Through jquery I am trying to target a div with an id within a div container with a different id. Example:
<div id="container-type-a">
<div id="inner_number_2201"></div> //<<<< this id is a passed dynamic ID and changes. Its passed into the function.
</div>
So I would want to do something like document.getElementById('> container-type-a' > 'inner_number_' + id + )
but this is not the right syntax. Can something like this be done?
ID should be unique in the HTML, so unless your HTML is malformed, you should be able to just
document.getElementById(id_In_Restaurant)
If you want to use a selector, you would use querySelector
var inner = document.querySelector("#container-type-a #inner_number_" + id_In_Restaurant);
But since ids are supposed to be unique, it makes no sense to use two ids. Just been to use getElementById
var inner = document.getElementById("inner_number_" + id_In_Restaurant);
Getting a reference to the parent element
var inner = document.getElementById("inner_number_" + id_In_Restaurant);
var innersParent = inner.parentElement;
Since Id is unique throughout the document so you can use the following syntax
$('#inner_number_' + unique_dynamic_id)
This will return you the jquery object of the element.
You can use below code if your dynamic div is direct decedent.
$('#'+$('#container-type-a >div').attributes.id.value)

How to read in an id element that has an href

I am trying to remove the content referenced by the following id:
<...id href="https://xyz'...>
My code:
var right = document.getElementById('https://xyz');
var parent = right.parentNode;
parent.removeChild(right);
The problem is when I reference the name of the id, it comes back as null. I tried document.getElementById('https://xyz').href, yet still null. Any suggestions?
Thanks.
You probably want to use document.querySelector:
var right = document.querySelector('[href="https://xyz"]');
or if you need the n-th match, document.querySelectorAll:
var right = document.querySelectorAll('[href="https://xyz"]')[n];
getElementById as the name suggests, selects an element by id so you have to define an id on your element: id="some_id" and then in JavaScript document.getElementById('some_id')
That's because you did not assign any ID to that tag. So document.getElementById('https://xyz') won't give you anything because there is no tag with this ID.
You have to assign an ID like this:
<...id="ID_of_href" href="https://xyz'...>
Then you can get it with:
document.getElementById('ID_of_href')
First of all we got to understand what is the html id attribute.
Definition and Usage
The id attribute specifies a unique id for an HTML element (the value
must be unique within the HTML document).
The id attribute is most used to point to a style in a style sheet,
and by JavaScript (via the HTML DOM) to manipulate the element with
the specific id.
According to this link: https://www.w3schools.com/tags/att_id.asp.
W3schools is a great web site for you to learn web development.
How to achieve your purpose:
const barElement = document.getElementById('bar');//Getting the element which id is bar.
console.log(barElement);
const fooElement = barElement.parentNode;//Getting bars parent.
console.log(fooElement);
<div id="foo">
<a id="bar" href="#"></a>
</div>

select a string after a substring in an element's class name

I have an element that contains an input text, to get the input text I'm using the jQuery method find.
The input text has a class name like this page-id-x with the x is variable, so I want to select that number after the substring page-id, and this is what I tried :
var id = ui.item.find('input').attr('class').split(/\s+/).filter(function(s){
return s.includes('page-id-');
})[0].split('-')[2];
console.log(id);
I think this code is too complicated, but I couldn't figure out some other way to do it.
If someone knows a better way, I'll be thankful.
Thanks in advance.
I'm going to assume the x part of page-id-x, not the id part, is what varies (since that's what your code assumes).
Another way to do it is with a regular expression, but I'm not sure I'd call it simpler:
var id = ui.item
.find('input')
.attr('class')
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
Example:
var ui = {
item: $("#item")
};
var id = ui.item
.find('input')
.attr("class")
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
console.log(id);
<div id="item">
<input class="foo page-id-23 bar">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The above makes the same assumptions your current code does, which are:
The first input in ui.item is the one you want
It will have the relevant class name
I assume those are okay, as your question is asking for an alternative, suggesting what you have is working.
As you're using jQuery, take a look at this: https://api.jquery.com/category/selectors/attribute-selectors/
For your case, you can use $('[class^="page-id-"'). These types of selectors (listed on the link above) actually work in CSS, too. (At least most should, if not all.)
To get the number after page-id-, my suggestion would be to store that number in some other HTML attribute, like data-pageID="1" or the like.
So you could have:
<div id="page-id-3" data-pageID="3">CONTENT</div>
Then, when you have the DOM element using $('[class^="page-id-"'), you can access that number with .attr('data-pageID').val().
If you can control the HTML markup, instead of using class names, you can use data attributes instead. For example, instead of:
<input class="page-id-1">
You can use:
<input data-page-id="1">
Then jQuery can find this element effortlessly:
$('[data-page-id]').attr('data-page-id')
You can find your element using the *= selector.
let elem = document.querySelector('[class*=page-id-]')
Once you have the element, you can parse the id out:
let [base, id] = elem.className.match(/page-id-(\d+)/)
console.log('page id: %s', 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>

Get value with javascript from a tag inside a tag

I need to extract data from such code:
<div class="rateCalc_InfoLine2">
<span style="font-size:12px;">
Text1 - <b><font color="red" size="2">$ 500</font></b>;
Text2 - <b><font color="red">$ 30</font></b>
</span>
</div>
So basically, I need to find the value 30 that is inside the 2nd font tag of the span tag that is inside div tag with the class rateCalc_InfoLine2. The structure is static, so I dont need to worry about mistakes ( only the value 30 will change )
I know hoe to get the value of the div like this:
$(".rateCalc_InfoLine2").html();
but how to get the specific one I need?
Answer: $(".rateCalc_InfoLine2 font").eq(1).html().replace('$ ', '');
You can first find the font elements within div using descendant selector and then use index to find the second element using eq().
Live Demo
$(".rateCalc_InfoLine2 font").eq(1).html();
Edit to remove the $
strResult = $(".rateCalc_InfoLine2 font").eq(1).html().replace('$ ', '');
$(".rateCalc_InfoLine2 font:eq(1)").html();
or
$(".rateCalc_InfoLine2 font:last").html();
Well, in this specific scenario you could do this:
$(".rateCalc_InfoLine2 font")[1].innerHTML;
To select the value from inside a tag you need to use html()
var value = $(".rateCalc_InfoLine2 font").eq(1).html();
Just try this:
$(".rateCalc_InfoLine2 font")[1].innerHTML;
Demo JSFiddle
The following would select the relevant element, access its textual content with the text() method, match() any numeric value inside it, and assign it to sum:
var price = $('.rateCalc_InfoLine2 font:eq(1)').text().match(/\d{1,}/);
if (price) { var sum = price[0]; }
In your example, sum would be assigned the value 30.

Categories