I have text on a page, its in a <h3> tag, which has a class ms-standardheader, but there are other texts on the page with the same class in its own <h3> tag. I also know the text I want to hide is 'Session'.
With this how can I write a javascript function to hide only this text?
Here is an image of the developtools from IE.
I'd suggest, if you're restricted (as your tags suggest) to non-library plain JavaScript, the following:
var h3s = document.getElementsByTagName('h3'),
classedH3 = [];
for (var i = 0, len = h3s.length; i < len; i++) {
if (h3s[i].className.indexOf('ms-standardheader') > -1) {
classedH3.push(h3s[i]);
}
}
for (var i = 0, len = classedH3.length; i < len; i++) {
if (classedH3[i].firstChild.nodeValue == 'the text to hide'){
classedH3[i].style.display = 'none';
}
}
JS Fiddle demo.
References:
push().
document.getElementsByTagName().
element.className.
node.nodeValue.
indexOf().
Can't you give the target element an ID? That would make things much more simple. Otherwise, you have to go through all <h3> elements until you find the one you want to hide:
var headings = document.getElementsByTagName("h3");
for(var i=0; i<headings.length; i++) {
var contentElement = headings[i].getElementsByTagName('nobr');
var content = "";
if(contentElement.length) {
content = contentElement[0].textContent ? contentElement[0].textContent : contentElement[0].innerText;
}
var content = contentElement.length ? contentElement[0].childNodes[0].nodeValue : '';
if(headings[i].className == 'ms-standardheader' && content == 'Session') {
headings[i].style.display = 'none';
}
}
you should try this :
window.onload = function()
{
getElementByClass('ms-standardheader');
}
window.getElementByClass = function(theClass){
var allHTMLTags=document.getElementsByTagName('*');
for (i=0; i<allHTMLTags.length; i++) {
if (allHTMLTags[i].className==theClass) {
var content = allHTMLTags[i].innerHTML;
var search = /session/;
if (search.test(content))
{
alert(search);
allHTMLTags[i].style.display='none';
}
}
}
}
See Demo : http://jsfiddle.net/3ETpf/18/
Always favour a unique Id where possible. If not possible then you have to manually traverse the DOM to find the elements you are looking for. Here's an example using getElementsByTagName().
var i, header, headers = document.getElementsByTagName('h3');
for (i = 0; i < headers.length; i += 1) {
header = headers[i];
if (header.className === 'ms-standardheader' &&
(header.textContent || header.innerText) === 'Session') {
header.style.display = 'none';
}
}
see: http://jsfiddle.net/whP5z/
If you have jquery you may type this :
$("h3.ms-standardheader:contains('Session')").hide();
Related
Site address: http://tcafe2a.com/bbs/board.php?bo_table=free
I want to remove a few posts done by user-id "captinharu".
I did the following(in Tampermonkey script) and it removed most of the webpages instead of just post done by 'captainharu' and I have no idea. Please help.
function rmvtd2(name) {
var t = document.getElementsByTagName("td");
for (var i=0; i<t.length; i++)
{
var elementHtml = t[i].outerHTML;
var n1 = elementHtml.indexOf(name);
if(n1>1){
t[i].style.visibility = 'hidden';
}
}
}
rmvtd2("captinharu");
For this particular case, this solution works. But may not be valid for all the cases.
function rmvtd2(name) {
var t = document.getElementsByTagName("tr");
for (var i=0; i<t.length; i++)
{
var elementHtml = t[i].outerHTML;
var n1 = elementHtml.indexOf(name);
if(n1 > -1 && n1 < 1000){
t[i].style.display = 'none';
}
}
}
rmvtd2("captinharu");
Maybe you can try with querySelectorAll()?
let name ='captinharu';
document.querySelectorAll('td').forEach(function (item){
const regex = RegExp(name);
if(regex.test(item.innerText)){
item.setAttribute('hidden',true);
// or -> item.classList.add('hidden');
// or -> item.remove();
};
})
DOM hide some thing. You can use simply javascript to manage them like
to hide ...
t[i].style.display = 'none';
to show ...
t[i].style.display = '';
You can hide the row by doing something like this:
function hideUserPost(username){
$("#tbl_board .member").each(function( index ) {
if($( this ).text() == username){
$( this ).closest('tr').hide();
}
});
}
hideUserPost('Captain Day');
I wan to collect all text from a list of elements obtains using
var elements =document.body.getElementsByTagName("*");
What I've done so far:
var text = '';
for (var i = 0; i < elements.length; i++) {
text = text + ' ' + elements[i].innerText
}
This will return duplicated text because it get the own text of each element plus its children's. I want to know if there is a way to get element's owntext using pure javasript?
I think the issue is that nested matching elements of a particular tag are being counted twice. The solution is to check if we've already visited a parent element and to skip the child if that's the case.
var text = '';
var visited = [];
for (var i = 0; i < elements.length; i++) {
var found = false;
for (var e = elements[i]; e != null; e = e.parentNode) {
if (visited.indexOf(e) > -1) {
found = true;
break;
}
}
if (!found) {
text = text + ' ' + elements[i].innerText;
visited.push(elements[i]);
}
}
http://jsfiddle.net/h8k0xx82/
This works perfectly fine, but for future reference I would like to know if there is a better way to do this.
document.getElementsByTagName('h1')[0].style.display = 'none';
document.getElementsByTagName("p")[0].style.display = 'none';
document.getElementsByTagName("p")[1].style.display = 'none';
document.getElementsByTagName("ul")[0].style.display = 'none';
document.getElementsByTagName("hr")[0].style.display = 'none';
I'm open to using jQuery if it would help.
While jQuery wasn't specifically requested, it would be the shortest implementation to meet the OP's sample code exactly as written:
$('h1:eq(0), ul:eq(0), hr:eq(0), p:lt(2)').hide();
Keep your nodes in an Array, then you can write some functions which will hide or show a whole Array (or NodeList) at once, e.g.
function display_none(nodelist) {
var i = nodelist.length;
while (i-- > 0)
nodelist[i].style.display = 'none';
}
function display_default(nodelist) {
var i = nodelist.length;
while (i-- > 0)
nodelist[i].style.display = '';
}
So you have
var elms = [
document.getElementsByTagName('h1')[0],
document.getElementsByTagName("p")[0],
document.getElementsByTagName("p")[1],
document.getElementsByTagName("ul")[0],
document.getElementsByTagName("hr")[0]
];
Now can simply do
display_none(elms); // hide them all
display_default(elms); // return to default
Here's a pure Javascript option that implements a jQuery-like extension for the :lt(n) pseudo selector so you can specify however many of each tag you want.
As the question asked, this operates on the first two "p" tags, then the first "h1", "ul" and "hr" tags:
function hideItems(selector) {
var r = /:lt\((\d+)\)/;
selector.split(',').forEach(function(item) {
var len, elems, i, m = item.match(r);
if (m) {
item = item.replace(r, "");
elems = document.querySelectorAll(item);
len = Math.min(+m[1], elems.length);
} else {
elems = document.querySelectorAll(item);
len = elems.length;
}
for (i = 0; i < len; i++) {
elems[i].style.display = 'none';
}
});
}
hideItems('p:lt(2),h1:lt(1),ul:lt(1),hr:lt(1)');
Working demo: http://jsfiddle.net/jfriend00/m9vspymz/
Using Pure JavaScript
//gets all DOM elements with a tag of p or li
var elems = document.querySelectorAll('p,li');
//loops over all elements
for(var i = 0;i < elems.length; i++)
{
//hides each element in the array
elems[i].style.display = 'none';
}
Code Specifically for you
var elems = document.querySelectorAll('p,h1,ul,hr');
for(var i = 0;i < elems.length; i++)
{
elems[i].style.display = 'none';
}
Here's the code (JavaScript):
var n = [ // 'tagname',which in order
'h1',0,
'p',0,
'p',1,
'ul',0,
'hr',0
];
for(var i = 0;i < elems.length)
{
document.getElementsByTagName(n[i*2])[(n[i*2]+1)].style.display = 'none';
i++;
i++;
}
I'm writing a script for CasperJS. I need to click on the link that contains a span with "1". In jQuery can be used :contains('1'), but what the solution is for selectors in pure Javascript?
HTML: <a class="swchItem"><span>1</span></a><a class="swchItem"><span>2</span></a>
jQuery variant: $('a .swchItem span:contains("1")')
UPD CasperJS code:
casper.then(function () {
this.click('a .swchItem *select span with 1*')
})
Since 0.6.8, CasperJS offers XPath support, so you can write something like this:
var x = require('casper').selectXPath;
casper.then(function() {
this.click(x('//span[text()="1"]'))
})
Hope this helps.
Try the following. The difference between mine and gillesc's answer is I'm only getting a tags with the classname you specified, so if you have more a tags on the page without that class, you could have unexpected results with his answer. Here's mine:
var aTags = document.getElementsByTagName("a");
var matchingTag;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].className == "swchItem") {
for (var j = 0; j < aTags[i].childNodes.length; j++) {
if (aTags[i].childNodes[j].innerHTML == "1") {
matchingTag = aTags[i].childNodes[j];
}
}
}
}
var spans = document.getElementsByTagName('span'),
len = spans.length,
i = 0,
res = [];
for (; i < len; i++) {
if (spans.innerHTML == 1) res.push(spans[i]);
}
Is what you have to do unless the browser support native css queries.
jQuery is javascript. There are also a number of selector engines available as alternatives.
If you want to do it from scratch, you can use querySelectorAll and then look for appropriate content (assuming the content selector isn't implemented) and if that's not available, implement your own.
That would mean getting elements by tag name, filtering on the class, then looking for internal spans with matching content, so:
// Some helper functions
function hasClass(el, className) {
var re = new RegExp('(^|\\s)' + className + '(\\s|$)');
return re.test(el.className);
}
function toArray(o) {
var a = [];
for (var i=0, iLen=o.length; i<iLen; i++) {
a[i] = o[i];
}
return a;
}
// Main function
function getEls() {
var result = [], node, nodes;
// Collect spans inside A elements with class swchItem
// Test for qsA support
if (document.querySelectorAll) {
nodes = document.querySelectorAll('a.swchItem span');
// Otherwise...
} else {
var as = document.getElementsByTagName('a');
nodes = [];
for (var i=0, iLen=as.length; i<iLen; i++) {
a = as[i];
if (hasClass(a, 'swchItem')) {
nodes = nodes.concat(toArray(a.getElementsByTagName('span')));
}
}
}
// Filter spans on content
for (var j=0, jLen=nodes.length; j<jLen; j++) {
node = nodes[j];
if ((node.textContent || node.innerHTML).match('1')) {
result.push(node);
}
}
return result;
}
I have a long table with many many columns and it looks really ugly for the users. What I wanted to do was create a simple button that would act as a switch, to turn on and off some of the columns.
Some of the columns are not needed, so what I did was add a class to every that wasn't needed, eg: ....
Now, what I thought I could do was this:
var hidden = 1;
function toggleTable(){
element_array = document.getElementsByClassName('disabled');
for(i = 0; i < element_array.length; i++){
if(hidden == 1){
element_array[i].style.display = 'none';
}else{
element_array[i].style.display = '';
}
}
if(hidden == 1) hidden = 0;
else hidden = 1;
}
This works for the most part in Firefox, but some quick tests in IE(7+8) and I get the following:
Message: Object doesn't support this property or method
Obviously indicating that IE doesn't want to let me simply change "display: none;" for something like table columns/rows.
I can't think of any workarounds. Ideally I'd like a fully cross-compatible solution to toggling the display of certain table columns,but if it's not compatible in the older browsers (eg: IE6) then that would also be OK.
The error that you're getting is not because IE doesn't want to set the display property, it's because the getElementsByClassName method isn't implemented in IE. If you want an implementation of that methods you can use this one which was written by Dustin Diaz.
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
Then you would re-write your method as follows.
var hidden = 1;
function toggleTable(){
var element_array = getElementsByClass('foo');
for(i = 0; i < element_array.length; i++){
if(hidden == 1){
element_array[i].style.display = 'none';
}else{
element_array[i].style.display = '';
}
}
if(hidden == 1) hidden = 0;
else hidden = 1;
}
toggleTable();
And what about jQuery.toggle()?
$(".disabled").toggle();