JavaScript & jQuery: HTML DOM

How to debug JavaScript?

[js]debugger[/js]

Work with string

How to split a string into an array?

  • Javascript

    [js]
    var text = ‘part1||part2||part3’;
    var labelArr = text.split(‘||’);[/js]

How to replace a string inside a string?

  • Javascript

    [js]
    var text = ‘abcdef_bdf’;
    text = text .replace(/b/g, “NEW”);[/js]

How to get/set element attribute?

Text box

  • Get attribute value

    [js]var ElementVal = $(this).attr(‘value’);[/js]

  • Set attribute value

    [js]var ElementVal = $(this).attr(‘value’, ‘abcde’);[/js]

Drop down list

  • Get attribute value

    [js]var ElementVal = $(this).val();[/js]

  • Set attribute value

    [js]var ElementVal = $(this).val(‘abcde’);[/js]

How to get text node next to an element

  • Use Javascript

    [js]
    var id = $(this).attr(‘id’);
    var textNode = document.getElementById(id).nextSibling;
    var textVal = textNode.nodeValue;
    [/js]

How to loop child nodes inside a table

  • Use Javascript

    [js]
    var tbls = $(‘[id$=”_TblSuffix”]’);
    tbls.each(function (index) {
    // Loop
    <table>
    $(“tr”, this).each(function( i ) {
    // Loop
    <tr>
    $(“td”, this).each(function( j ) {
    // Loop
    <td>
    });
    });
    });[/js]

How to jump to an anchor?

  • Method 1

    [js]function scrollTo(elementID) {
    location.hash = “#” + elementID;
    }[/js]

  • Method 2

    [js]document.getElementById(“element_id”).scrollIntoView(true);[/js]

  • Method 2 is better than method 1 because you can use method 1 only once for the page url is changed to

    [js][/js]

    http:/xxxxxxx.com#element_id

    [js][/js]

How to get/set value of a URL parameter?

  • Get URL parameter value

    [js]
    function getParameter(url, parameter) {
    var params = url.substr(1).split(‘&’);
    for (var i = 0; i < params.length; i++) {
    var p=params[i].split(‘=’);
    if (p[0] == parameter) {
    return decodeURIComponent(p[1]);
    }
    }
    return false;
    }[/js]

  • Set URL parameter value

    [js]
    function updateUrlParameter(uri, key, value) {
    // remove the hash part before operating on the uri
    var i = uri.indexOf(‘#’);
    var hash = i === -1 ? ” : uri.substr(i);
    uri = i === -1 ? uri : uri.substr(0, i);

    var re = new RegExp(“([?&amp;amp;])” + key + “=.*?(&amp;amp;|$)”, “i”);
    var separator = uri.indexOf(‘?’) !== -1 ? “&amp;amp;” : “?”;

    if (uri.match(re)) {
    uri = uri.replace(re, ‘$1’ + key + “=” + value + ‘$2’);
    }
    else
    {
    uri = uri + separator + key + “=” + value;
    }
    return uri + hash; // finally append the hash as well
    }
    [/js]

How to empty all child nodes

  • Javascript

    [js]while (node.firstChild) {
    node.removeChild(node.firstChild);
    }[/js]

If.. else… in one line

[js]
var variable = (condition) ? (true block) : ((condition2) ? (true block2) : (else block2))
// if() { … } else if() { … } else { … }
[/js]

How to loop a drop down list, get text & value, set selected option?

[js]
// Loop
$(“#dropdownID option”).each(function()
{
// Get text
var Text = this.text;

// Get value
var Val = this.value;

// Set selected option
if (Text.indexOf(“option to be selected”) >= 0)
{
$(“#dropdownID”).val(Val);

// Break
return false;
}
});
[/js]

How to count occurences of text inside a string

[js]
var count = (‘your string’.match(/your text/g) || []).length;
[/js]

Table DOM

Get table tag > tr tag > td tag

var elms = document.getElementsByTagName('table');
for (var i = 0; i < elms.length; i++) {
    // -Get- var tableElem = elms[i];
    var trElem = tableElem.getElementsByTagName("tr")[12];
    var tdElem = trElem.getElementsByTagName("td")[3];
    var tdText = tdElem.innerText;

    // -Do- Change font size
    tdElem.style.fontSize = '14px';
}

How to get nth td from a first tr node

console.log($(tr[0]).find('td').eq(n).text());

jQuery DOM

How to get all direct children elements?

$("#colorSwatchContent > span")

How to get first direct child element?

$("#colorSwatchContent > span:first")

How to check if a drop down list has selected option or not?

var hasSelected = ($('#dropDownlist > [selected]').length > 0);
if (!hasSelected)
{
    // If no, this sample doesn't have selected option

    // Add blank selection
    $("#dropDownlist").prepend("<option value='0'></option>");
    $("#dropDownlist").val('0');
}

How to get parent, child element, element attribute by jQuery

Get parent

var parentElem = $(this).parent();

Get last child

var lastElem = parentElem.children().last();

Get value of attribute

var bgColor = lastElem.attr("bgcolor");

Set value of attribute

$(this).attr('onmouseover', onMouseOver);

Insert new Element

// Current Element
var currentElem = ...

// New element
var newDIV = document.createElement('div');
newDIV.setAttribute('style', 'height:10px;width:650px;');

// Parent element
var parentElem = currentElem.parentElement;

// Sibling element
var nextElem = currentElem.nextElementSibling;

// Insert new element
parentElem.insertBefore(newDIV, nextElem);

How to find element by DOM path?

//Example - Hide the first tr of a table element. This table element is a child element of 'strID' element

$("#" + strID + " > table > tbody > tr").each(function (index) {
     if (index == 0) {
         // First child
         this.style.display = "none";
         return false; // break
     }
});

How to get elements basing on id’s prefix or suffix?

Get elements basing on id’s prefix “start_”

var tdElements = $('[id^="' + 'start_' + '"]');
    tdElements .each( function(index) {
    alert(index);
});

Get elements basing on id’s suffix “_end”

var tdElements = $('[id$="' + '_end' + '"]');
    tdElements .each( function(index) {
    alert(index);
});

Get elements basing on id’s suffix “_end” inside an element

var parentElem = document.getElementById('parentElement');
if (qaElem != null)
{
    var tdElements = $(parentElem).find($('[id$="' + '_end' + '"]'));
    tdElements .each( function(index) {
        var hiddenId = $(this).attr('id');
    });
}

Get elements basing on prefix and suffix

var foundElem = $('input[id^="prefix"][id$="sufix"]');
foundElem .each( function(index) {
    $(this).attr('type', 'hidden');
});

Vanilla Javascript

Get element list by tag name

const allElements = document.getElementsByTagName('fullformhistory')

Convert HTML Collection to Javascript array

const currentHorseElements = [...allElements]?.filter((element) => {
  ...
})

Get attribute of an element

const currentHorseElements = [...allElements].filter((element) => {
  const foundHorseCode = element?.getAttribute('horseCode')
  return foundHorseCode === horseCode
})

Be the first to comment

Leave a Reply

Your email address will not be published.


*