Joao
Joao

Reputation: 67

How to use jquery content with Vanilla js

I am trying to make it so that this code I wrote doesn't rely on having to access the dom in order to use its contents. I had already accessed the dom once before using jquery, and I want to be able to use the jquery I wrote instead of writing new code to access it. Here is my code so far:

  constructor($navigation, $content) {

    if ($navigation.length == 0 || $content.length == 0) {
      return;
    }

    var nav1 = document.getElementById("main-nav");
    var btns = nav1.getElementsByClassName("nav");
    for (var i = 0; i < btns.length; i++) {
      btns[i].addEventListener("click", function () {
        var current = document.getElementsByClassName("active");
        current[0].className = current[0].className.replace(" active", "");
        this.className += " active";
      });
    }
    $navigation.on('click', 'li', function () {
      $content.hide();
      $($content[$(this).index()]).show();
    });
  }

And here is where I had accessed the dom in another document:

   new Faq($("#main-nav"), $("div[class='faq-container']"));

what I want to do is make is so that var nav1 and var btns can make use of $navigation and $content, instead of accessing the dom directly. Do I have to somehow convert this code to jquery? how would I approach that?

Upvotes: 0

Views: 2601

Answers (1)

fdomn-m
fdomn-m

Reputation: 28611

Reading the question as:

I have already accessed the DOM once using jquery, and I want to be able to use this variable with vanilla javascript rather than access the DOM a second time

To get the DOM node from a jquery object, you add [0] or .get(0)

function example(jqueryObj)
{
    jqueryObj[0].innerText = "set via [0]";
}

example($("#div"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div"></div>

Specific to the question, to convert between $("#main-nav") and the doc.getElementById("main-nav") equivalent, you would use

var nav1 = $navigation[0]

As a bonus, here's your function jquery-ified

constructor(navigation, content) {

  if (navigation.length == 0 || content.length == 0) {
    return;
  }
  
  navigation.on("click", ".nav", function() {
      $("nav.active").removeClass("active");
      $(this).addClass("active");
  });

  navigation.on('click', 'li', function() {
    content.hide();
    $(content[$(this).index()]).show();
  });
}

new Faq($("#main-nav"), $("div.faq-container"));

Upvotes: 1

Related Questions