Hide parent `<div>` if child do not have element `<ul>` [duplicate] - javascript

This question already has answers here:
jQuery - rule for "does not contain element"
(2 answers)
Closed 8 years ago.
<div id="I">
<h3></h3>
<div class="C">
<ul>...</ul>
</div>
</div>
Using JQuery or JavaScript, how can I hide the whole id="I" element if the element <ul> does not exist?

You can use the following Jquery to determine if a ul element exists inside of the div with id="I"
$(document).ready(function(){
var size = $("#I ul").length;
if (size === 0)
$("#I").hide();
});
JsFiddle
EDIT:
I've updated my script since it wouldn't work if you have multiple div tags with an id of "I". Based on your description, you would like to remove all div tags with id of "I" that do not contain a ul element. Here is the updated JsFiddle that meets your question's requirement: enter link description here
Here is the code to do just that:
$(document).ready(function(){
$("div").each(function(index, element){
var id = $(this).attr("id");
var numOfUl = $(this).find("ul").length;
if (id == "I" && numOfUl === 0){
$(this).hide();
}
});
});

Try this:
$("#I:not(:has(>ul))").hide();
DEMO

$.fn.isNot = function(trueFalse) {
var elem = $(this);
var _isNot = elem.is("*");
var _parent = $(elem.selector.split(" ").slice(0, 1)[0]);
return _isNot
? trueFalse(_isNot, elem, _parent)
: trueFalse(_isNot, _parent)
};
$("#I ul").isNot(function(trueFalse, parent) {
console.log(trueFalse, parent);
if (!trueFalse) {
parent.hide()
};
});
http://jsfiddle.net/guest271314/ns09astu/

Related

Select element by tag/classname length

I'd like to select an element using javascript/jquery in Tampermonkey.
The class name and the tag of the elements are changing each time the page loads.
So I'd have to use some form of regex, but cant figure out how to do it.
This is how the html looks like:
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
The tag always is the same as the classname.
It's always a 4/5 letter random "code"
I'm guessing it would be something like this:
$('[/^[a-z]{4,5}/}')
Could anyone please help me to get the right regexp?
You can't use regexp in selectors. You can pick some container and select its all elements and then filter them based on their class names. This probably won't be super fast, though.
I made a demo for you:
https://codepen.io/anon/pen/RZXdrL?editors=1010
html:
<div class="container">
<abc class="abc">abc</abc>
<abdef class="abdef">abdef</abdef>
<hdusf class="hdusf">hdusf</hdusf>
<ueff class="ueff">ueff</ueff>
<asdas class="asdas">asdas</asdas>
<asfg class="asfg">asfg</asfg>
<aasdasdbc class="aasdasdbc">aasdasdbc</aasdasdbc>
</div>
js (with jQuery):
const $elements = $('.container *').filter((index, element) => {
return (element.className.length === 5);
});
$elements.css('color', 'red');
The simplest way to do this would be to select those dynamic elements based on a fixed parent, for example:
$('#parent > *').each(function() {
// your logic here...
})
If the rules by which these tags are constructed are reliably as you state in the question, then you could select all elements then filter out those which are not of interest, for example :
var $elements = $('*').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
DEMO
Of course, you may want initially to select only the elements in some container(s). If so then replace '*' with a more specific selector :
var $elements = $('someSelector *').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
You can do this in vanilla JS
DEMO
Check the demo dev tools console
<body>
<things class="things">things</things>
<div class="stuff">this is not the DOM element you're looking for</div>
</body>
JS
// Grab the body children
var bodyChildren = document.getElementsByTagName("body")[0].children;
// Convert children to an array and filter out everything but the targets
var targets = [].filter.call(bodyChildren, function(el) {
var tagName = el.tagName.toLowerCase();
var classlistVal = el.classList.value.toLowerCase();
if (tagName === classlistVal) { return el; }
});
targets.forEach(function(el) {
// Do stuff
console.log(el)
})

div#d1 toggle on p#1 click - howTo?

I am trying to toggle a div when its name is clicked.
I have multiple coupls like that in my page, and I want it to work as
"when <p id= "d2"> is clicked => <div id="d2"> is toggled".
I tried those functions:
$(document).ready(function(){
$("p").click(function(){
$("div#" + $(this).attr('id')).toggle();
});
});
function rgt() {
//document.body.innerHTML = "";
var id = "d" + this.id;
var situation = document.getElementById(id).style.display;
if (situation == "none") {
situation = "block";
}
else {
situation = "none";
}
}
function showHide(theId) {
if (document.getElementById("d" + theId).style.display == "none") {
document.getElementById("d" + theId).style.display = "block";
}
else {
document.getElementById("d" + theId).style.display = "none";
}
}
I can't make it Work!!! Why is it?
the browser says:"no 'display' property for null"...
I will be more than happy to solve it with simple jquery
Ensure Your id Attributes Are Unique
Assuming that your id attributes are unique, which they are required to be per the specification:
The id attribute specifies its element's unique identifier (ID). The
value must be unique amongst all the IDs in the element's home subtree
and must contain at least one character. The value must not contain
any space characters.
You should consider renaming your id attributes to d{n} and your paragraphs to p{n} respectively as seen below :
<button id='p1'>p1</button> <button id='p2'>p2</button> <button id='p3'>p3</button>
<div id='d1'><pre>d1</pre></div>
<div id='d2'><pre>d2</pre></div>
<div id='d3'><pre>d3</pre></div>
which would allow you to use the following function to handle your toggle operations :
$(function(){
// When an ID that starts with P is clicked
$('[id^="p"]').click(function(){
// Get the proper number for it
var id = parseInt($(this).attr('id').replace(/\D/g,''));
// Now that you have the ID, use it to toggle the appropriate <div>
$('#d' + id).toggle();
})
});
Example Using Unique IDs
You can see an interactive example of this approach here and demonstrated below :
Consider Using data-* Attributes
HTML supports the use of data attributes that can be useful for targeting specific elements through jQuery and associating them to other actions. For instance, if you create an attribute on each of your "p" elements as follows :
<button data-toggles='d1'>p1</button>
<button data-toggles='d2'>p2</button>
<button data-toggles='d3'>p3</button>
and then simply change your jQuery to use those as selectors :
$(function(){
// When an element with a "toggles" attribute is clicked
$('[data-toggles]').click(function(){
// Then toggle its target
$('#' + $(this).data('toggles')).toggle();
});
});
Is this you are looking?
$("#p1").on("click", function() {
$("#d1").toggle();
});
js fiddle: https://jsfiddle.net/Jomet/09yehw9y/
jQuery(function($){
var $toggles = $('.divToggle');
var $togglables = $('.togglableDiv');
$toggles.on('click', function(){
//get the div at the same index as the p, and toggle it
$togglables.eq($toggles.index(this)).toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="divToggle">Show Me 1</p>
<p class="divToggle">Show Me 2</p>
<p class="divToggle">Show Me 3</p>
<div class="togglableDiv">Weeee 1</div>
<div class="togglableDiv">Weeee 2</div>
<div class="togglableDiv">Weeee 3</div>
Minimal approach using classes. This solution assumes the order of the p elements in the dom are in the same order as the divs are in the order. They do not have to be contiguous, but the order does matter with this solution.
ids are not the droids you are looking for.
An id needs to be unique. If you want to classify something one would suggest to use classes. You can actually use serveral of them for some fancy stuff. How about something like this:
<p class="toggle one">one</p>
<div class="toggle one" style="display:none">content one</div>
Straight forward. Every element that is a switch or switchable gets the class toggle. Each pair of switch and switchable(s) gets an additional identifier (like one, two, ...).
Simple JScript Implementation:
Now how about not using JQuery to work with that? Sure it i$ handy, but it hides all that neat stuff one would eventually like to learn her/himself!
var myToggle = {};
(function(module) {
"use strict";
(function init() {
var elements = document.getElementsByClassName("toggle");
var element;
var i = elements.length;
while (i) {
i -= 1;
element = elements[i].className;
elements[i].setAttribute("onclick", "myToggle.swap(\"" + element + "\")");
}
}());
module.swap = function(element) {
var couple = document.getElementsByClassName(element);
var i = couple.length;
while (i) {
i -= 1;
if (couple[i].style.display === "none" && couple[i].tagName === "DIV") {
couple[i].style.display = "block";
} else if (couple[i].tagName === "DIV") {
couple[i].style.display = "none";
}
}
};
}(myToggle));
<p class="toggle one">one</p>
<div class="toggle one" style="display:none">content one</div>
<p class="toggle two">two</p>
<div class="toggle two" style="display:none">content two 1</div>
<div class="toggle two" style="display:none">content two 2</div>
var myToggle = {} is the object we use to keep our little program contained. It prevents that our code conflicts with other declarations. Because what if some plugin on our site already declared a function called swap()? One would overwrite the other!
Using an object like this ensures that our version is now known as myToggle.swap()!
It may be hard to follow how it got to that name. Important hint: something looking like this... (function() { CODE } ()) ...is called an immediately-invoked function expression. iffy! It's a function that is immediatly executed and keeps its variables to itself. Or can give them to whatever you feed it in the last ()-pair.
Everything else is as verbose as can be... no fancy regular expressions, hacks or libraries. Get into it!

Changing text with Jquery after a Div [duplicate]

This question already has answers here:
How do I select text nodes with jQuery?
(12 answers)
Closed 8 years ago.
Is it possible to use JQuery to hide the input elements plus the text after the input? The code is generated, so I cannot change the text, wrap it in a span or alter it in any way.
<label>Event Location <span class="req">*</span></label><br>
<input type="radio" name="a22" id="a22_0" value="Lafayette LA">Lafayette LA<br>
<input type="radio" name="a22" id="a22_1" value="Houston TX">Houston TX<br>
<input type="radio" name="a22" id="a22_3" value="San Antonio TX">San Antonio TX
You need to iterate the parent elements (TDs in your example added as an answer), find all the text elements that follow a radio button, then wrap them in hidden spans:
e.g.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/6gzfLorp/3/
$('td').contents().each(function (e) {
if (this.nodeType == 3 && $(this).prevAll(':radio').length) {
$(this).wrap($('<span>').hide());
}
});
Note: Your question is a little ambiguous, but it would appear from your answer you have TDs which you could just hide all contents of the TD using:
http://jsfiddle.net/TrueBlueAussie/6gzfLorp/7/
$('.set-cities td').each(function (e) {
$(this).contents().wrapAll($('<span>').hide());
});
It is wrapped in a td tag. Here's what I have for now:
$("label:contains('Event Location')").parent("td").wrap("<span class='set-cities'></span>");
$('.set-cities').empty();
$('.set-cities').append("<td><label>Event Location <span class='req'>*</span></label><br><input type='radio' name='aa2' id='aa2_1' value='Houston TX' checked='checked'>Houston TX<br></td>");
I just going to change the whole block of text rather than just the city name.
In case you wanted to replace the text node directly, here's a way to do it. I borrowed from https://stackoverflow.com/a/298758/728393 and tailored it to your situation
function replaceTextAfter(selector,newtext){
var textnode = $(selector).parent().contents() // we need to contents as a collection
.filter(function(){
return this.nodeType == 3 && $(this).prev().is($(selector)); //return true if node is text and the previous node is our selector
});
textnode[0].data = newtext; //change the text
}
replaceTextAfter('#a22_0','abc');
http://jsfiddle.net/z606no23/
Thi delete all text after an element done, until a new tag
http://jsfiddle.net/alemarch/hm7ey6t5/
function deleteElemPlusText( elem ) {
var contestoHtml = $(elem).parent().html()
var thisHtml = $(elem).get(0).outerHTML // $(elem).outerHTML()
var re = new RegExp(thisHtml + "([^<])*")
var newContesto = contestoHtml.replace(re, "")
$(elem).parent().html(newContesto)
}
function deleteAllElemsPlusText( toDelete ) {
var x = $(toDelete).length;
for (var i = 0; i < x; i++) {
deleteElemPlusText($(toDelete).eq(0))
}
}
deleteAllElemsPlusText( "input[type=radio]" )
note: not all browser have outerHTML properties access, but you can use this jquery plugin http://www.darlesson.com/jquery/outerhtml/

Find a value within a div and replace

I have 3 values that I need to replace within 3 divs.
<div class="bx-pager-item">
<a class="bx-pager-link active" data-slide-index="0" href="">1</a>
</div>
<div class="bx-pager-item">
<a class="bx-pager-link" data-slide-index="1" href="">2</a>
</div>
<div class="bx-pager-item">
<a class="bx-pager-link" data-slide-index="2" href="">3</a>
</div>
I need to replace 1, with the value 'test'; 2 with the value 'test1'; and 3 with the value 'test2'.
I have tried the following code without any success, any help would be appreciated.:
$(document).ready(function() {
var fandreplace = document.getElementsByClassName('bx-pager-item').innerHTML.replace('3', 'test2');
});
You should loop each element and replace their values accordingly.
Replace based on Index
$('.bx-pager-link').text(function (i, v) {
return 'test' + (i > 0): (i - 1): '';
});
Replace based on value
$('.bx-pager-link').text(function (i, v) {
var val = parseInt(v, 10);
return 'test' + (val > 0): (val - 1): '';
});
You need to individually set them since the new html will be unique (you could do a loop depending on what you really want to replace it with).
Here's a simple way to change the inner html using the "index" of each element.
fiddle
$(document).ready(function() {
$('.bx-pager-item:eq(0)').html('test');
$('.bx-pager-item:eq(1)').html('test1');
$('.bx-pager-item:eq(2)').html('test2');
});
In jquery you would do
$('.bx-pager-item > a').each(function(){
var str = $(this).text().replace('3', 'test2');
$(this).text(str);
});
and if you wanted several values
var map = {'3':'test2', '1':'test'};
$('.bx-pager-item > a').each(function(){
$(this).text(map[$(this).text()]);
});
JSFiddle: http://jsfiddle.net/rNLvU/
$('.bx-pager-item').each(function(){
var $this = $(this);
$this.text('test'+$this.text().trim());
});
note the text needs trimming in this instance as a leading space can occur in the element's text() value
Try this : use each to select all the elements
$(document).ready(function(){
$('.bx-pager-link').each(function (i, elem) {
$(elem).text('test '+i);
});
});

is there a way to check a divs id and class in jquery

I wanted to refine the question and be more specific lets say I wanted to search through divs with a certain class name. ex.
<div id ="1" class="head"></div>
<div id ="2" class="head"></div>
<div id ="3" class="head"></div>
if(div.id != "1")
{
add class to all divs not = 1
}
how would this work
thank you
If div is an Element object:
if (div.id == 'blah' && div.className == 'blablah') {
If div is a given jQuery object, use the .is() method, combined with the id (#) and class (.) selector:
if (div.is('#blah.blahblah')) {
If you want to check if there's any <div> which matches these rules:
if ($('div#blah.blahblah').length) {
You can get the div's ID using $(div).attr('id') or div.id. As for class, you can check .hasClass.
if($(div).attr('id') === 'blah' && $(div).hasClass('blahblah'))
given the markup:
<div class='myhappyclass other' id='yodudeid'>hi</div>
$('div').each(function() {
var myi = $(this).attr('id');
var myc = $(this).attr('class');
alert("id:" + myi + " class:" + myc);
if (myi == 'yodudeid' && $(this).hasClass('other')) {
alert('yepper');
}
});
The following show work, but not tested.
if(($('#blah').length) && ($('.blahblah').length)){
then do this
}
From your little example above, to achieve this, just do:
$(document).ready(function(){
$("div[id!=1]").addClass('{your class name}');
});
If you actually wanted to check for a specific element with id and class you could take advantage of the jquery each function which loops through elements matching your criteria as follows:
$('div').each(function(){
if($(this).attr('id') == '2' && $(this).attr('class') == 'head')
{
$(this).addClass('{your class name}');
}
});

Categories