I am trying to use html() function of jquery over the specific child like:
<div id="main">
<p>I am p tag</p>
<span> i am span tag</span>
</div>
Now if we use $("#main").html() it gives both p and span but if i want only p, what should i do?
Try like below,
$("#main p").html()
This will give me I am p tag but i want <p> I am p tag</p>
Try below for outerHTML,
$('#main p')[0].outerHTML
Or you can make it as jQuery function so you can chain.
jQuery.fn.outerHTML = function(s) {
var _this = this[0];
return _this.outerHTML?_this.outerHTML:(s ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html());
};
$('#main p').outerHTML()
DEMO: http://jsfiddle.net/skram/PMjKR/1/
Ref: Get selected element's outer HTML
Many ways depending on your exact requirements.
Standard css selector:
$('#main p').html();
filtering on children.
$('#main').children('p').html();
by getting the first child of main
$('#main:first-child').html();
EDIT
after seeing comment on another answer by OP i will simply add where html() is replace with [0].outerHTML
see selectors here
Related
I am trying to get the text inside a <h4> that is closest to my clicked icon <i>
The following registers the click OK, but it does not return the value inside the h4. Instead, it returns a very long array of details as you can see, too long for Codepen:
<p class="icon heart">
<i>icon</i>
</p>
<h4>this text</h4>
$('body').on('click', '.icon.heart i', function(e){
var property = [];
console.log('clicked!');
console.log($(e).closest( ".intro-text h4" ));
});
Where am I going wrong?
http://codepen.io/franhaselden/pen/pboYvZ
EDIT:
I have updated the HTML to be more representative of my code layout. How can I access the content inside the <h4>?
https://jsfiddle.net/0jsxjqzx/3/
Your first problem is that e is an Event object, not a DOM Element.
You, presumably, mean this or e.target
You then have a second problem (which I didn't notice at first because you failed to include the HTML in the question, I fixed that for you).
Look at the documentation of closest:
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
The h4 is not an ancestor of the italic text! So it won't be found.
You need to go up to the paragraph and then find its sibling instead.
$(this).closest("p").next("h4");
You can do it like this:
$(document).ready(function() {
$('body').on('click', '.icon.heart i', function() {
var property = [];
console.log('clicked!');
console.log($(this).closest(':has(.intro-text)').find('h4').html());
});
});
Full example here: https://jsfiddle.net/cn8trrhn/
You were missing the closing parenthesis on the last console.log.
h4 is not a parent of i, so closest won't work, you may want to use nextAll .
jQuery(document).ready(function() {
$('.iconheart').on('click', function(){
var property = [];
console.log('clicked!');
console.log($(this).nextAll( "h4" ).html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="iconheart">
<i>icon</i>
</p>
<h4>this text</h4>
i have a simple question about JQuery...
I have a main <div> containing some divs, which have dynamical ids. each child div has a <h4> tag in it. These h4 does not have any id, nor class, nor name. They just have some text in it.
Here is what i'm talking about :
<div id="main_div">
<div id ="div01">
<h4>Sometext01</h4>
</div>
<div id ="div02">
<h4>Sometext02</h4>
</div>
<div id ="div03">
<h4>Special Text!!!</h4>
</div>
<div id ="div04">
<h4>Sometext04</h4>
</div>
</div>
I would like to get the parent div's id of the h4 which text is "Special text!!!" (so, here, in this example, it is div03).
But, unfortunately, these ids are auto generated (by Sugarcrm, for those who know), and i can't know by advance the id's name. So that is why i have to pass by the h4.
I know i can use the jQuery function below to pass through all h4
allMyH4.each()
And i know i can use the jQuery function below to find the parent of my desired h4
myFoundH4.parent()
But i'm getting some trouble on searching the h4 by their text() (or html() )
Could you please help me on that?
Thanks a lot
EDIT few hours later :
Thanks to #Bhushan , i could do what i really wanted. It just has a restriction : my user MUST not change h4 texts NOR giving several h4 the same name containing my string.
For another solution, try #rory too, it did not work for me, but it had been tested by others, and it seems to be better than contains.
You can use filter():
var $h4 = $('h4').filter(function() {
return $(this).text() == 'Special Text!!!';
});
console.log($h4.parent().prop('id'));
This will ensure an exact match on the text property, not a partial match as the :contains selector will give. filter should also be faster.
Try this :
$(function(){
var parentId = $('main_div').find('h4:contains("Special Text!!!")').parent().attr('id');
});
Have you tried :contains()?
var divId = $("h4:contains('Special Text!!!')").parent().attr('id');
If there's other <h4> tags containing text which includes your Special Text!!!, but you don't want to select them, you can use .filter() as #Rory's answer says:
var divId = $("h4:contains('Special Text!!!')").filter(function(i, elt) {
return $(elt).text() === 'Special Text!!!';
}).parent().attr('id');
However if you have multiple <h4>s with this text, it could still match multiple elements.
$("h4").each(function(inx, elem){
var pattern = "Special Text!!!", el = $(elem);
if(el.text() == pattern){
console.info(el.parent().attr("id"));
}
});
Update: Roy McCrossan has a good solution.
Try this:
FIDDLE
$("h4").each(function(){
if($(this).text() === 'Special Text!!!')
{
var pid = $(this).parents().attr("id");
alert(pid);
}
});
I want to select the following three values from the HTML file either by Jquery or Javascript.
class "class1" href value
class "class1" inner text value (PersonA in the example code)
class "Title" inner text value (Accountant in the example)
How can I select all the data of li node by node as? I am lost :(
<ol id="result-set">
<li id="v-0">
<div class="result-data">
..
<h2>
<a class="class1" href="">PersonA</a>
</h2>
<dl class="basic">
<dt>Title</dt>
<dd class="title">Accountant</dd>
....
</dl>
</div>
</li>
<li id="v-1">
...
</li>
.....
To get "PersonA": $('#v-0 h2 a').html();
To get href of that link: $('#v-0 h2 a').attr('href');
To get "Accountant": $('#v-0 dl dd').html();
You can modify the id ("v-0") at the start of the selector to choose a particular "row" of your data set.
With jQuery, you can do something like this:
$("#result-set li").each(function() {
var $currentLi = $(this),
$class1link = $currentLi.find("a.class1"),
class1href = $classAlink.attr("href"),
class1content = $classAlink.html();
// do something with values
});
The .each() method will process each li element. Within the callback to .each() the variable $currentLi is a jQuery object holding that li (set from $(this) where this is the li element itself). The .find() method is used to find the anchor element within the li and then its href and content are retrieved.
The "Accountant" you asked about is one item in a definition list, so you'd probably want to loop through that list with another .each() statement nested inside the one above.
You don't make it clear how you want to use the values, but this should get you started. For further details about the various jQuery methods I've mentioned check the jQuery API.
document.getElementById(Id).value
returns value of element with specific id. in jquery:
$("#id").val()
by class $(".yourClass").val()
to get attribute value use attr("attributeName") for example $(".class1").attr('href').
if you want to get text from specified element use .text() like $(".title").text() //will return Accountant.
You mean selecting them with a jQuery selector? That would be done like so:
$('.class1').attr('href') //class1 href, i persume you dont mean classA as it doesnt exist in your code
$('.class1').text(); //PersonA text using the same selector
$('.title').text(); //Accountant from the .title dd
i want to read all links in ".vm-video-title"-divs and post them each in the same div. So i made this script:
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("div.vm-video-title>a").text());//add to div the link
});
but i have the problem that it reads ALL the links of all divs and put them in one div.
example:
<div class="vm-video-title">Text1</div>
<div class="vm-video-title">Text2</div>
<div class="vm-video-title">Text3</div>
output:
Text1Text1Text2Text3
Text2Text1Text2Text3
Text3Text1Text2Text3
wanted output:
Text1Text1
Text2Text2
Text3Text3
You can select the <a> elements directly, and use the after()[docs] method to append the content of each after each one respectively.
$("div.vm-video-title > a").after(function() { return $(this).text(); });
This doesn't do a "destroy then recreate" of the existing elements like the html()[docs] method will.
Working example: http://jsfiddle.net/CCr9C/
This should do the job for you,
you need to find the div inside current element in the loop (el).
$('.vm-video-title').each(function(i, el) {
el = $(el);
el.html(el.html()+el.find("a").text());
});
in your code you are adding text() of all matching "a" tags in your divs (i.e. Text1Text2Text3)
You were almost there. Instead of : $("div.vm-video-title").text(), which gives you text inside any div with class vm-video-title, you need to find a tag inside current div and get text from it. We pass this as context for selecting a inside current div jQuery( selector, [context] )
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("a", this).text());
});
I want to find all the div which must are having one and onlyone anchor next to it with JQuery
i.e
<div>
</div>
<a></a>
<div>
</div>
<div>
</div>
<a></a>
For example above acc to my requirement I want to the first and third as the output ?
In these cases, go backwards from the anchor, like this:
$("a").prev("div")
This gets the <a> elements, then gets the <div> immediately before if it's a <div> using .prev().
$("div").filter(function() {
return $(this).next("a").length;
}).hide();
Try it here.
This gives all anchors following a div
var els = $("div + a")
so building on Nick's answer this should work
var els = $("div + a").prev();
see http://api.jquery.com/category/selectors/
and specifically Next Adjacent Selector
Making sure that there is only one anchor after the div means doing a little more filtering
You can find all divs with more than one anchor directly following using
$("div + a + a").prev().prev();
so could use that if you need to exclude that case.
Try it here: http://jsfiddle.net/ySuZm/2/