How can I get a <p> element in a <td>? - javascript

I want to get a "p" element which is inside a "td". How can I get it? My code is:
<td id="mytd">
<p> aaaa </p>
<p> bbbbb </p>
<p id="myp"> cccc </p>
</td>
I can get the td using. document.getElementById("mytd"), but I don't know how to get the p with id="myp".

Just use exactly the same code getElementById, but use the ID of the <p> instead of the <td>:
var p = document.getElementById("myp");
p.style.background = "#000";
p.style.color= "#FFF";
Here's a jsFiddle showing it working.

document.getElementById("myp")
If you output valid HTML, your IDs you use for DOM elements should be unique for the whole document. Thus, you can do something as simple as this. If this doesn't work (got more elements with this ID), deal with that problem instead. IDs should be unique.

you could try this jQuery as well :
var p = $("td#mytd p#myp");
Then you can get html or text p.html(); or p.text();
Correction :
I don't think td#anyid(tag name is redundant) is necessary because IDs are unique in document you need those only if you were using classes so I think should do(if you use jQuery that is) :
var p = $("#myp");

with jQuery
$("p[id$='myp']")

Related

How add ID to HTML href with javascript

I have an HTML like this
<div class="this">
EXP
</div>
I want to add id to <a>. But do not know what to do.
First select your element using something like .getElementsByClassName(). Keep in mind that .getElementsByClassName() returns a NodeList collection of elements, so you'll want to access the first index (or loop over them). You can then simply set the ID with .id, as the ID is merely a property of an element.
This can be seen in the following:
const element = document.getElementsByClassName('this')[0];
element.id = 'element';
console.log(element);
<div class="this">
EXP
</div>
If you want to add this with Javascript, you'll need to use a selector to target your <a> tag and then set the id attribute on it. You can do this by using the querySelector() function or as seen below:
// Find an <a> tag that occurs below a class called "this" and set its id attribute
document.querySelector('.this > a').id = "some-id";
There are many other available functions to handle this through native Javascript and other frameworks, so your milage may vary depending on what you are using.
Example
In this example, we have provided some CSS that should only apply to an element with an id of "test" and we'll run the necessary code to show that the id is being added to the element (as it will be red):
document.querySelector('.this > a').id = 'test';
#test { color: red; }
<div class="this">
EXP
</div>
Add the id attribute to the <a> tag. See the differences of the middle line:
<div class="this">
<a id="expid" href="exp.com">EXP</a>
</div>

How to find all elements that contain a certain attribute in Javascript?

Consider the following code
<button az-name="btn1">A sample button</button>
<p>A sample text</p>
<p az-name="p1">Another sample text</p>
Now I have to get reference to the button element and the 2nd paragraph element. How can I accomplish this in Javascript or jQuery?
With Jquery you can use the attribute selector, as follows:
Either, to find the p/button with the particular attribute:
$button = $("button[az-name]");
$parag = $("p[az-name]");
Or, to find any tags with the particular attribute:
$button = $("[az-name='p1']");
$parag = $("[az-name='btn1']");
Or mix the both solutions.
Note that you can use also that :
Attribute Contains Selector [name*="value"]: Selects elements that have the specified attribute with a value containing the a given substring
like this :
$all_az = $("[az-*='btn1']");
To get all tags which have an attribute begining with "az-" for example.
You can use
$("[az-name]")
For tweaking- plunker
For reference - attribute selector

Jquery :contains selector without children

I need to do a function to change color (in this example) of dom element in javascript(jquery) but i have some trouble with :contains selector but i need to use because i don't have specific ID or class.
HTML :
<p id="title">John</p><!-- contain John must be red -->
<div id="description">John</div><!-- contain John must be red -->
<div id="element">
<p id="element1">John</p><!-- contain John must be red -->
<p id="element2">Anonymous</p><!-- dont contain John dont change color -->
</div>
ID in this code just to show you my problem.
Js :
$("div:contains('John'), p:contains('John')").css("color", "red");
Problem :
This script make unwanted changes (#element2)
I already check : Jquery doc but to simple dom in this example .
Testable example here : JSFIDDLE
Try to use exclude the div with other elements,
$("div:contains('John'):not(:has(*)), p:contains('John')").css("color", "red");
If your html have chances of containing elements like this,
<div id="description">John<p>test</p></div>
Then ultimately you have to go along with #TrueBlueAussie's answer.
DEMO
You could create your own filter that removes children elements and checks the textNodes of the current element only.
As the string you're trying to match is present in the comments as well, any use of innerHTML is out, so textContent is used.
$("#bug").on('click', function () {
$("div, p").filter(function() {
var clone = this.cloneNode(true);
while (clone.firstElementChild) {
clone.removeChild(clone.firstElementChild);
}
return clone.textContent.indexOf('John') != -1;
}).css("color", "red");
});
FIDDLE

How to remove a span in-place?

I have the following input:
<p>
<span class="highlight">
Some text <b>that can have formatted components too</b>.
</span>
And some more text here of course.
</p>
And I want to achieve the following output:
<p>
Some text <b>that can have formatted components too</b>.
And some more text here of course.
</p>
I am using jquery and it has a .unwrap() function, but if I go
$('.highlight').unwrap() it removes <p>. :(
Manually hacking the DOM seems like a hassle. Do you know any short solution?
With the use of .contents() you'll get the elements inside of the parent element you want to remove.
$(".highlight").contents().unwrap();
try replace with
$('.highlight').replaceWith(function() {
return $(this).html();
});
You can simply can do this by using jQuery.
var cnt = $(".highlight").contents();
$(".highlight").replaceWith(cnt);
Quick links to the documentation:
contents( ) : jQuery
replaceWith( content : [String | Element | jQuery] ) : jQuery

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