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
Related
I need to be able to select and modify an element in an HTML document. The usual way to find an element using jQuery is by using a selector that selects by attribute, id, class or element type.
However in my case I have the element's HTML DOM and I want to find the element on my document that matches this DOM.
Important :
I know I can use a class selector or ID selector etc.. but sometimes the HTMLs I get don't have a class or an ID or an attribute to select with, So I need to be able to select from the element's HTML.
For example here is the element I need to find :
<span class='hello' data='na'>Element</span>
I tried to use jQuery's Find() but it does not work, here is the jsfiddle of the trial : https://jsfiddle.net/ndn9jtbj/
Trial :
el = jQuery("<span class='hello' data='na'>Element</span>");
jQuery("body").find(el).html("modified element");
The following code does not make any change on the element that is present in my HTML and that corresponds to the DOM I have supplied.
Is there any way to get the desired result either using native Javascript or jQuery?
You could filter it by outerHTML property if you are sure how browser had parsed it:
var $el = jQuery("body *").filter(function(){
return this.outerHTML === '<span class="hello" data="na">Element</span>';
});
$el.html("modified element");
el = jQuery('<i class="fa fa-camera"></i>');
This does not say "find the element that looks like <i class="fa fa-camera"></i>". It means "create a new i element with the two classes fa and fa-camera. It's the signature for creating new elements on the fly.
jQuery selectors look like CSS, not like HTML. To find the i element with those two classes, you need a selector like i.fa.fa-camera.
Furthermore $("document") looks for an HTML element called document. This does not exist. To select the actual document, you need $(document). You could do this:
$(document).find('i.fa.fa-camera').html("modified html")
or, more simply, you could do this:
$('i.fa.fa-camera').html('modified html');
You indicate in a comment to your question that you need to find an element based on a string of HTML that you receive. This is, to put it mildly, difficult, because, essentially, HTML ceases to exist once a browser has parsed it. It gets turned into a DOM structure. It can't just be a string search.
The best you can do is something like this:
var searchEl = jQuery('<i class="fa fa-camera"></i>');
var tagName = searchEl.prop('tagName');
var classes = [].slice.apply(searchEl.prop('classList'));
$(tagName + "." + classes.join('.')).html('modified html');
Note that this will only use the tag name and class names to find the element. If you also want IDs or something else, you'd need to add that along the same lines.
You should use Javascript getting the elements by something like
document.getElementById...
document.getElementsByClassName...
document.getElementsByTagName...
Javascript is returning the elements with the Id, Class or Tag Name you chose.
You can get en element with document.querySelector('.fa-camera')
with querySelector you can select IDs and Classes
You can simply refer to it by its class names.
$('.fa.fa-camera').html("modified html");
Similar to this answer https://stackoverflow.com/a/1041352/409556
Here is a full example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.fa.fa-camera').html("modified html");
});
</script>
</head>
<body>
<i class="fa fa-camera"><h1>Some HTML</h1></i>
</body>
</html>`
The one thing that you could use is to check attributes (class and id goes here too in some way) that element have, and the build jQuery selector or DOM querySelector to find the element you need. The hardest part would be to find element based on innerHTML property - "Element" text inside it, for this one you'll probably have to grab all similar element and then search through them.
<span class='hello' data='na'>Element</span>
jQuery('body').find('span.hello[data=\'na\']').html('modified element')
Take notice of 'span' - that's tag selector, '.hello' - class, '[data="na"]' data attribute with name of data.
Jsfiddle link here that extends your example;
I have a simple structure like:
HTML
<ul id="costsDropdown">
<li data-position="bla bla"></li>
</ul>
and I want to change each "data-position" attribute of my list Elements.
My first Jquery Shot was this here:
$("#costsDropdown ul").each(function() {
$("li").attr("data-position", "TEST-VALUE123");
});
but it doesnt work, I think my selector are wrong...
could anyone give me a hint please?
Thanks for any help!
Greetz
Your selectors are a bit off
$("#costsDropdown ul").each
That is trying to select the child ul of the container #costsDropdown (which is the ID of the ul) - what you want is:
$("#costsDropdown li").each(function() {
$(this).attr("data-position", "TEST-VALUE123");
});
ID's are unique - no need to double up the selector with an ID and the type of element it is.
Note that I used $(this), not $("li"), inside the each callback. $("li") selects all li elements, anywhere on the page; we just want a jQuery wrapper for the one specific one we're handling inside the each.
In fact, the each is completely unnecessary because of the set-based nature of jQuery; if you use the .attr setter, it sets the attribute on all elements in the set:
$("#costsDropdown li").attr("data-position", "TEST-VALUE123");
That will set the value on all of the li elements inside #costsDropdown.
If you need to set separate individual values on the individual li elements, you still don't need each (though it's fine if you want to use it); you can use the version of attr that accepts a callback that it uses to find out what value to set:
$("#costsDropdown li").attr("data-position", function(index) {
return "Test value " + index;
});
That will set "Test value 0" on the first li, "Test value 1" on the second, etc. And like the each example above, if you need to, you can use this within the callback to refer to the li for that call (possibly using $(this) to wrap it if you need a jQuery wrapper).
$("#costsDropdown ul") matches no elements, it has to be $("#costsDropdown") (#costsDropdown is the ul).
And even that is unnecessary. Go
$("li[data-position]").attr("data-position", "TEST-VALUE123");
instead.
I am trying to clone an li element but without the tags.
I am have tried many different ways but I can make it seem to work.
When I take a look at the html of the li element it still selects the span tags.
Below is the code I am using. Any help would be really appreciated. Thanks!
<ul class="todo_list_items" data-category_id="44">
<li class="tasks" data-task_id="30">
<!-- Don't want to select this span class -->
<span class="modify_tasks">
<a href='#' class='delete_task_name'>Delete</a>
<a href='#' class='edit_task_name'>Edit Task</a>
</span>
Test
</li>
</ul>
<script>
$(document).on("click", ".edit_task_name", function () {
var task_id = $(this).data("task_id");
var previous = $(".tasks[data-task_id=30]").not(".tasks[data-task_id=30] > span").clone();
console.log(previous.html());
});
</script>
Just clone it and then empty it:
var previous = $(".tasks[data-task_id=30]").clone().empty();
EDIT: If you only want to remove the span and not other content, then just remove the span from the clone:
var previous = $(".tasks[data-task_id=30]").clone();
previous.children("span").remove();
not() will check against elements in the set, in your case the set consists of only $(".tasks[data-task_id=30]"). not() is testing the span inside it to see if it matches its own parent, so not wont be adjusting your jQuery object for cloning there. An alternative way to achieve what you want might be code similar to this:
var $tasks = $(".tasks[data-task_id=30]"),
$modifyTasks = $tasks.children('span').detach(),
$cloneOfTasks = $tasks.clone();
$modifyTasks.prependTo($tasks);
$cloneOfTasks.appendTo($tasks.parent());
.detach() removes the span without losing events and data so you can put it back in when your done making your clone.
Alternatively this code might be easier to interpret and use:
var $tasks = $(".tasks[data-task_id=30]");
$('ul.todo_list_items').append($tasks.contents().not('span').clone().wrap('<li class="tasks" data-task_id="30">').closest('li'));
This uses .contents() to grab whats inside the task so you can run not against it. The closest('li') part is needed to ensure the li wrapped around the new element is returned for appending to the ul.
My HTML looks like this:
<ul>
<div class="topmsg"></div>
<li>
<div id="message"></div>
....</li>
....</ul>
and this list is repeated several times
I could get the div inside the li like this:
li.children('div#message').hide();
Any ideas on how to get the topmsg using jquery or JS?
Ignoring the problems with your HTML.
As you have an ID on the div you want to select, you should just be able to use the # id selector.
$('#topmsg')...
If you have multiple things with the id of topmsg then you really need to reform your HTML so that you don't.
Id is short for "identifier" and should be unique in a document - it is used to uniquely identify the node.
EDIT after topmsg changed from id to class:
Having changed topmsg to be a class, then once you have the LI that contains the message you're interested in you can traverse it with a parent and then a find.
E.g.
// Get the LI that contains the message DIV
var messageLi = $('#message').parent();
// Hide it
messageLi.hide();
// Get the 'topmsg' relating to that LI
messageLi.parent().find('.topmsg').hide();
Use this code, it will get the div relative from the li.
var topmsg = $(li).parent();
I have a blob of HTML that I'm retrieving using simple jQuery selectors, something like the following:
<div id="stuff">
<ul>
<li>some</li>
<li class="ninja">stuff</li>
</ul>
</div>
I'm basically doing:
var myblock = $("#stuff").html();
now I want to inject an additional li element to the bottom of that li list with very similar attributes to the li above it, but i want to change the class ninja to class samurai.
What's the best way of going about that with jQuery?
Simply select the <ul> and append the <li> to it
$("#stuff ul").append('<li class="samurai">stuff</li>');
If you actually wanted to copy the last <li> element, change the class then add to the list, then you could do something like this
var ul = $("#stuff ul");
ul.append(ul.find('li:last').clone().removeClass().addClass("samurai"));
pass true into clone() if you also want to copy event handlers too.
The problem with taking a whole chunk of HTML, changing an element and then reinserting is that any event handlers set up on elements that will be replaced when you reinsert the HTML will be lost, so it's more elegant/ and less cumbersome/intrusive to simply manipulate the part of the DOM that you need to.