Get only direct element value with jquery - javascript

Lets say I have the following for my menu:
$(document).ready(function() {
alert($('ul li').html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
<li><i class="font-icon"></i> Users
<ul>
<li>Overview</li>
</ul>
</li>
</ul>
As you can see as a return I get:
<i class="font-icon"></i> Users
<ul>
<li>Overview</li>
</ul>
Now the problem is that I'm only interested in: <i class="font-icon"></i> Users. Is there a way to only get that as a return without putting it in a div or span? I already tried with .text() but this only gave me the actual text Users (obviously).
Thanks in advance

I think this could be the solution: DEMO
$(document).ready(function() {
var i=$('ul li').html();
var ul=$('ul li').find('ul')[0].outerHTML;
i=i.replace(ul,'');
alert(i);
});

Use the remove() method. It's removes child elements matching a selection:
$(document).ready(function() {
var elem = $('ul li').html().remove('ul');
alert(elem);
});

Related

How can I select the first specific inner element?

Here is my HTML?
<ul>
<li>
<a href="./link1">
<div>something</div>
<span>link</span>
</a>
</li>
</ul>
And this is my jQuery code:
$('li').on('click', function(){
var link = $(this).find('a').attr('href');
})
As you see, there is two <a> tags. And .find() refersh to both of them. While I just want to select the <a> which is right inside (one level) in the <li> tag. So expected result is ./link.
What alternative should I use instead of .find() ?
You can use the direct descendant selector.
$('li').on('click', function(){ var link = $(this).find('> a').attr('href'); })
Try with eq(0) .It will get the first a tag
Or
Do with first('a')
$(this).children().first('a').attr('href')
$('li').click(function(){
console.log($(this).children('a').eq(0).attr('href'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>click
<a href="./link1">
<div>something</div>
<span>link</span>
</a>
</li>
</ul>
Method 1: Using Jquery's children and first
$('#myList').on('click', function() {
var link = $('#myList').children('a').first();
console.log(link.attr('href'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul>
<li id="myList">
<a href="./link1">
<div>something</div>
<span>link</span>
</a>
</li>
</ul>
Method 2: Using the immediate children selector >
$('#myList').on('click', function() {
var link = $('li > a:first');
console.log(link.attr("href"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul>
<li id="myList">
<a href="./link1">
<div>something</div>
<span>link</span>
</a>
</li>
</ul>
the first specific element
What alternative should I use instead of .find() ?
$(this).find('a:first')
seems like only logical solution and easy to read by developer
Don't do so. How is the browser meant to know which link to follow? It'd be invalid HTML
I suggest you using this instead:
startmiddleend
As you can see start and end are linked to page1 but the middle points to page2.

How Get Name Class With Javascript?

Hi everyone i need get name class menu li for load this page
html
<body>
<div class="menu">
<ul>
<li class="page2" id="page2">PAGE TOW</li>
<li class="page3" id="page3">PAGE THREE</li>
</ul>
</div>
<div class="load"></div>
</body>
js
$(document).on('click','.menu li',function(){
var Get_Name_Class = //Get Name Class
if(/* var Get_Name_Class*/).hasClass("page2")) {
$(".load").load('page2.php');
}
else if(/* var Get_Name_Class*/).hasClass("page3")) {
$(".load").load('page3.php');
}
});
how can i this ( get id or class not difference )
Use this to refer the clicked element inside the handler callback.
$(document).on('click','.menu li',function(){
// cache the reference
var $this = $(this);
// check using the cached element
if($this.hasClass("page2")) {
$(".load").load('page2.php');
}
else if($this.hasClass("page3")) {
$(".load").load('page3.php');
}
});
You can do it using jQuery. If it is class you can do:
$(".className")
if it is id you can do:
$("#idName")
if it is just html element you can do:
$("elementName")
Pass this.className with ".php" concatenated to .load()
$(document).on('click','.menu li',function() {
$(".load").load(this.className + ".php")
});
$(document).on('click','.menu li',function(){
// cache the reference
var $this = $(this);
// check using the cached element
if($this.hasClass("page2")) {
$(".load").load('page2.php');
}
else if($this.hasClass("page3")) {
$(".load").load('page3.php');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="menu">
<ul>
<li class="page2" id="page2">PAGE TOW</li>
<li class="page3" id="page3">PAGE THREE</li>
</ul>
</div>
<div class="load"></div>
</body>
use "#" symbol for id so your code becomes
("#idname")
or u can use "this" which points to the present class u are working on
Don't use classnames. One day you'll add an extra class to those elements and your site will stop working and you'll be left wondering why - or in the worst case it'll slip unnoticed.
Say you have one or even more buttons for page2 triggering - than it's the perfect place to use the data-* attribute!
$(document).on('click', '[data-load]', function() {
var page = $(this).data("load");
console.log(page); // Just to test
$(".load").load(page +'.php');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-load="page2">PAGE TWO :) me too</a>
<div class="menu">
<ul>
<li data-load="page2">PAGE TOW</li>
<li data-load="page3">PAGE THREE</li>
</ul>
</div>
<div class="load"></div>

Add extra pair of UL using JavaScript/JQuery

I have done coding the first part HTML then JavaScript/JQuery. Now I want to surround the final common list with a UL need to be done using JavaScript/JQuery. So the final common list will be surrounded by two UL instead of one. Eg
Final Outcome
<ul id="CommonLister">
<ul> <!--Need to add this-->
<li class="columnItem">John</li>
<li class="columnItem">Mark</li>
</ul><!--Need to add this-->
</ul>
Current Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul id="listOne">
<li class="columnItem">John</li><!--will be removed and put under CommonLister-->
<li class="columnItem">James</li>
<li class="columnItem">Mary</li><!--will be removed and put under CommonLister-->
</ul>
<ul id="listTwo">
<li class="columnItem">John</li><!--will be removed and put under CommonLister-->
<li class="columnItem">Mark</li>
<li class="columnItem">Mary</li><!--will be removed and put under CommonLister-->
</ul>
<ul id="CommonLister">
<li class="columnItem">John</li>
<li class="columnItem">Mark</li>
</ul>
</div>
$(function() {
$('#run-code').on('click', function(e) {
e.preventDefault();
//What were you doing? nope.
var currentItems = {}; //Blank object
var $mergeColumn = $('#CommonLister'); //Common list reference
$('.columnItem').each(function(i, el) {
var $el = $(el); //Notation I use to differentiate between the regular HTML Element and jQuery element
if (!currentItems.hasOwnProperty($el.html())) {
//Has this name come up before? if not, create it.
currentItems[$el.html()] = []; //Make it equal to a brand spanking new array
}
currentItems[$el.html()].push(el);
//Add the item to the array
});
$.each(currentItems, function(name, data) {
//Loop through each name. We don't actually use the name variable because we don't care what someone's name is
if (data.length > 1) {
//Do we have more than 1 element in our array? time to move some stuff
$.each(data, function(i, el) {
var $el = $(el); //See note above
if (i == 0) {
//If this is the first element, let's just go ahead and move it to the merge column ul
$el.appendTo($mergeColumn);
} else {
$el.remove(); //Otherwise, we've already got this element so delete this one.
} //end if/else
}); //end $.each(data)
} //end if data.length >1
}); //end $.each(currentItems)
}); //end $.on()
}); //end $(
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="run-code" class="btn btn-success">Click Me</button>
<h4>List 1</h4>
<ul id="listOne">
<li class="columnItem">John</li>
<!--will be removed and put under CommonLister-->
<li class="columnItem">James</li>
<li class="columnItem">Mary</li>
<!--will be removed and put under CommonLister-->
</ul>
<h4>List 2</h4>
<ul id="listTwo">
<li class="columnItem">John</li>
<!--will be removed and put under CommonLister-->
<li class="columnItem">Mark</li>
<li class="columnItem">Mary</li>
<!--will be removed and put under CommonLister-->
</ul>
<h4>Common List</h4>
<ul id="CommonLister">
<!--Extra ul will be added here-->
</ul>
It's invalid nesting a ul directly in a ul like this but if you have to, you could use jquery wrapAll:
$( "li" ).wrapAll( "<ul></ul>" );
See fiddle: https://jsfiddle.net/9xLt6d9f/
I agree with charlietfl that it seems strange to do it this way. However, to answer your question, the best way to force this improperly formatted HTML code would be hardcode it into your original file. Try the following code for the end of your file:
<h4>Common List</h4>
<ul id="CommonLister">
<ul id="CommonListerSub">
<!--Extra ul will be added here-->
</ul>
</ul>
Then, simply change one line of your code:
var $mergeColumn = $('#CommonListerSub'); //Common list reference
This will force it to list the list items under the nested ul tags.
I hope this is an acceptable solution. If for some reason it doesn't work, please comment as to what additional limitations you have, and perhaps share the link of the page that is giving you the required template or format specifications.

Refer to nested HTML elements with jQuery

I have some extensive HTML element in the following (simplified) format:
<div id="firstdiv" class="container">
<ul>
<li id="4"> <a title="ID:4">Tree</a>
<ul>
<li id="005"> <a title="ID:005">Leaf Tree</a>
<ul>
<li id="10"> <a title="ID:10">Fruit Tree</a>
<ul>
<li id="0050338"> <a title="ID:0050338">Apple Tree</a>
<ul>
<li id="399"> <a title="ID:399">Green Apple Tree</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li id="005"> <a title="ID:005">Conifer</a>
<ul>
<li id="10"> <a title="ID:10">Pine Tree</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
I want to access the value of the title attributes of all a-tags inside the div-container with the id="firstdiv" on click.
I tried the following jQuery function but it didn't work:
$("#firstdiv").children("a").on('click', function () { /*some code here*/ });
Any ideas what I'm doing wrong?
children() only goes one deep try find()
$("#firstdiv").on('click', function () {
$(this).find('a').each(function(){
console.log($(this).attr('title'))
})
});
will get all a tags titles when the #first_div is clicked
$("#firstdiv a").on('click', function () {
console.log($(this).attr('title'))
});
will get the title of the a tag you clicked on
children() does what it says, looks at child nodes only - not descendant nodes also. For that, you need find(). However, you need neither in your case, just a change to your selector.
$('#firstdiv a')
As with CSS, a space in the selector denotes a child OR descendant.
According to the jQuery documentation
The .children() method differs from .find() in that .children() only
travels a single level down the DOM tree while .find() can traverse
down multiple levels to select descendant elements (grandchildren,
etc.) as well
So change your selector to:
$("#firstdiv").find("a").on("click", function () {});
This will search everything beneath #firstdiv in your DOM tree.
Or even:
$('#firstdiv a').click(function(){
... do stuff
});
That will select all 'a' elements within #firstdiv
Try this http://jsfiddle.net/ApfJz/22/
$("#firstdiv a").on('click', function () { alert($(this).attr('title')); });
Demo
$(document).ready(function() {
$('#firstdiv a').click(function(){
alert($(this).attr('title'))
});
});
$("#firstdiv").find("a").on('click', function () {
});

changing value of unordered list when selecting li item

My question is, how do i change value of original element in UL list, after selecting/picking one li item under.
Example: I want to pick City3 and when i do, instead of "Pick City" it should be the value of "city3".
This is my jsfiddle.
This is HTML:
<div class="menu1">
<li class="naslov"><b>Pick City</b></li>
<div class="submenu1">
<ul id="sel">
<li value="1"><b>City1</b></li>
<li value="2"><b>City2</b></li>
<li value="3"><b>City3</b></li>
<li value="4"><b>City4</b></li>
<li value="5"><b>City5</b></li>
</ul>
</div>
Also is it possible not to change any of the css/html(With that i mean, i dont want to add select,option elements), and make it work just over some JQuery/JS functions?
Thanks,
Milos
$('#sel a').click(function(){
$('li.naslov b').html(this.innerHTML);
return false;
});
Live DEMO
Try this as your JS...
$(document).ready(function(){
$('.menu1').hover(function(){
$('.submenu1').stop(true).slideToggle('slow');
});
var orig = $(".naslov").html();
$("#sel li").hover(function(){
$(".naslov").html($(this).text());
}, function(){
$(".naslov").html(orig);
});
});
Another possible way to do this. In this case, the li could be dynamic, based on an AJAX feed or some other JavaScript.
$('#sel').on('click','li',function() {
$('li.naslov b').text($(this).text());
});
jsFiddle

Categories

Resources